Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize a android webview after adding data in it

In a layout (linear, vertical) hierarchy I've got several views and one of them is a WebView. They all have same parameters:

android:layout_width="fill_parent"
android:layout_height="wrap_content"

For all views, the spacing between elements is correctly handled but for the Webview there is a lot of spaces after the displayed text inside.

I set the (HTML) text of the webview in the "onCreate" method of the activity using the layout.

Is there a way to let the webview resize itself, to match its content size?

By the way, the space left vary from one device to another (emulator vs Milestone vs Hero)

Any idea? Thanks


1 Answers

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.

like image 99
Chitranshu Asthana Avatar answered Sep 16 '25 08:09

Chitranshu Asthana