Android WebView getContentHeight() always returns 0

android, android-webview

Solution

this is because the `onPageFinished` callback means the WebView has finished reading the bytes from the network, just that. At the point `onPageFinished` is fired the page may not be even parsed yet.

If your webview's height is set to wrap_contents then you could do something like this:

WebView v = new WebView() {
    @Override
    public void onSizeChanged(int w, int h, int ow, int oh) {
        super.onSizeChanged(w, h, ow, oh); // don't forget this or things will break!
        Log.d(TAG, "WebView height" + getContentHeight());
    }
};

If your webview is not wrap_contents then one option is to do what josedlujan suggested in his answer to this question and fetch the height from JavaScript.

Another option would be to use the deprecated `PictureListener`:

webview.setPictureListener(new PictureListener() {
    int previousHeight;
    @Override
    public void onNewPicture(WebView w, Picture p) {
        int height = w.getContentHeight();
        if (previousHeight == height) return;
        previousHeight = height;
        Log.d(TAG, "WebView height" + height); 
    }
});

Problem

I am implementing an WebView such that it can resize its height according to the content height. I tried to do the following: ``` WebView view = new WebView(context); view.loadData(htmlString, "text/html", "utf-8"); view.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); Log.d("2", view.getContentheight() + ""); // Set the height of the webview to view.getContentHeight() here? } }); Log.d("1", view.getContentHeight() + ""); ``` Where htmlString is a String of HTML format. However both the two Logs return 0. I am not sure if I am doing the right thing. How can I know the content height then set the height of the WebView accordingly?

Original source

Related problems