Resizing webview to match the content size

There has been lots of discussion around methods of resizing the webview to fit the size of its content.

The actual issue can be seen when we are using webview inside a scrollview. In case we wish to show something on top of webview and allow the whole page to scroll, if web view content goes beyond screen size.

If at first we load huge data in webview, it expands itself to fit the whole content, but when we load a smaller data later, it still shows the same previous size, which is way more than size required to display smaller data. Side effect of this is that user can keep scrolling beyond the html content.

Following are few threads where this issue has been discussed.

As you can see, most of the people suggest not to use webview inside scroll, and others suggest creation of new instances of webview every time we load a url into it. But both of these are not real solution to the problem.

Here is a small trick which worked for me.

private void setupWebView() {
    webView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
    webView.addJavascriptInterface(this, "MyApp");

public void resize(final float height) {
    MyActivity.this.runOnUiThread(new Runnable() {
        public void run() {
            webView.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));


  1. Hi.
    Does this example counting on reloading webView with new content?
    What if I want my webView to resize only when orientation is changed, without changing html code?
    I tried to invoke loadUrl in “onConfigurationChanged()”, but still, can´t make it work.
    Could you please help me?

  2. Hi, it seems that such solution doesn’t work if webview is placed inside scrollview and height of webview content if bigger than one screen. In this case it just shows the empty but scrollable space

    1. Hi Sergii, this workaround was done to handle this specific scenario of webview inside scrollview. My initial experience was that it works in all the cases except when we have “show more..” kind of web content. But in case you are observing something different then kindly share more information.

  3. Hi
    I have a issue

    webView.loadUrl -> ok, it work
    webView.loadData -> it don’t work

    How to use loadData?
    Thanks, sorry for my english.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s