Elyes Jlassi
Elyes Jlassi

Reputation: 272

android resize webView

I want to create and resize a WebView in background, I will not show it or append it to a layout, I just want to create it, resize it and load things in background.
My problem is that even after resizing using setLayoutParams I'm getting 0 for Height and Width.
Here's what I did:

public void createAndResizeWebView(Context context) {

    WebView webView = new WebView(context);

    System.out.println("webView: " + webView.getWidth());
    System.out.println("webView: " + webView.getHeight());

    webView.setLayoutParams(new LinearLayout.LayoutParams(300, 400));

    System.out.println("webView: " + webView.getWidth());
    System.out.println("webView: " + webView.getHeight());
}

I get :

webView: 0

webView: 0

webView: 0

webView: 0

Any help will be greatly appreciated!

Upvotes: 1

Views: 3616

Answers (2)

marcin.kosiba
marcin.kosiba

Reputation: 3231

Layout in android is asynchronous. Try overriding the WebView onSizeChanged method to get notified when the webview's size changes. Alternatively you could also use a ViewTreeObserver but that's less efficient.

The WebView gets the size from it's view parent. Since you're not attaching the webview to a view it won't get sized at all and you need to force that by calling

webview.layout(0, 0, width, height);

note that the above is only one of the many methods that get called on the webview when it's in the view hierarchy. The implementation might change to depend on more/different calls in the future. A more future-proof way would be to insert the webview into your view hierarchy and set it's visibility to INVISIBLE.

Upvotes: 1

Mongi Zaidi
Mongi Zaidi

Reputation: 1041

I think you should print the width and height of the webView like this:

System.out.println("webView: " + webView.getLayoutParams().width);
System.out.println("webView: " + webView.getLayoutParams().height);

Upvotes: 0

Related Questions