Android get height of webview content once rendered

后端 未结 5 1410
忘了有多久
忘了有多久 2020-12-14 18:44

I\'m trying to get the height of a webview once it has been rendered. It always returns null, I\'ve tried getHeight, getMeasuredHeight, getCo

5条回答
  •  感情败类
    2020-12-14 19:29

    Tried and tested the following:

        mWebView = new WebView(this);
        mWebView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    
            @Override
            public void onLayoutChange(View view, int l, int t, int r, int b, int ol, int ot, int or, int ob) {
                Log.i("demo", String.format("%s: top=%d, bottom=%d, content height=%d",
                        Thread.currentThread().getStackTrace()[2].getMethodName(), t, b, mWebView.getContentHeight()
                ));
            }
    
        });
    

    Logs:

    12-20 16:08:33.969 1466-1466/yourPkg I/demo: onLayoutChange: top=0, bottom=0, content height=0
    12-20 16:08:33.970 1466-1466/yourPkg I/demo: onLayoutChange: top=0, bottom=0, content height=0
    12-20 16:08:34.061 1466-1466/yourPkg I/demo: onLayoutChange: top=0, bottom=1510, content height=0
    12-20 16:08:34.091 1466-1466/yourPkg I/demo: onLayoutChange: top=0, bottom=1510, content height=2050

    The last one is correct.
    ViewTreeObserver sometimes gave me the wrong height.

提交回复
热议问题