Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView adding strange empty space at the bottom

I'm trying to add more empty space to a loaded WebView using JavaScript.

I load data using loadDataWithBaseUrl() from a String resource. Then, after measuring some content, I need to make WebView bigger, say for 100 pixels. So I call javascript function using loadDataWithBaseUrl():

mWebView.loadUrl("javascript:addHeight()");

Javascript function is defined in the original HTML:

function addHeight() { " +
    var elemDiv = document.createElement('div');
    elemDiv.style.cssText = 'height:100px;'; 
    document.body.appendChild(elemDiv); 
} 

After this, WebView resizes itself to fit the new content. However, resulting height is not originalSize + 100px, but bigger. I don't know where's the problem. I can't determine the target size, because it depends on the size of the appended div and it will be always different.

Has anybody tried this? Are you familiar with this behaviour?

like image 881
Hawk Avatar asked Sep 30 '15 20:09

Hawk


1 Answers

I found the next solution. There used JS callback. I hope this helps you. This change in size should work better than dynamic.

    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)));
        }
    });
}

And of see paragraph 4 of this list. Good luck!

like image 139
user2413972 Avatar answered Sep 21 '22 23:09

user2413972