Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

layout - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...