How to resize a android webview after adding data in it

I am sure this is too late but adding the method which worked for me in case somebody else comes here looking for solution.

Once the page finishes loading, I am injecting a javascript method to callback me JS hook. And in this method I am passing the size of .

    private void setupWebView() {
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            webView.loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
            super.onPageFinished(view, url);
        }
    });
    webView.addJavascriptInterface(this, "MyApp");
}
@JavascriptInterface
public void resize(final float height) {
    MyActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            webView.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));
        }
    });
}

The same solution can also be seen here.


It seems that at the moment the Webview only resizes itself if the content is too big. If the webview is bigger then the content it doesn't shrinks to reclaim the space.


I had the same problem. I solved by changing the visibility of the WebView.

mWebView.setVisibility(View.GONE);
mWebView.loadData(".....");
mWebView.reload();
mWebView.setVisibility(View.VISIBLE);

After some hours of searching and trying I found the simplest working solution. Just call this as "repaint":

webView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

For my webview it works perfectly inside a scrollView. If you do not want to use WRAP_CONTENT, you can use your own params.


I only put the webview inside the ScrollView and set layout_height=wrap_content and it worked.

<ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/web_scrollview"
        android:layout_below="@id/question_title_section"
        android:layout_marginBottom="60dp"
        android:scrollbars="vertical">
        <WebView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/question_content"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:padding="4dp">
        </WebView>
    </ScrollView>

And in my Activity

wvQuestion = (WebView) findViewById(R.id.question_content);
wvQuestion.loadUrl(url);