加载Android后获取WebView Content高度

Ant*_*wan 5 html android webview

我正在尝试在Webview上应用展开折叠功能基于其内容高度,但我总是得到错误的值这是我的代码

public class MesuredHeightWebView extends WebView {
    public MesuredHeightWebView(Context context) {
        super(context);
    }

    public MesuredHeightWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MesuredHeightWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }



    @Override
    public void invalidate() {
        super.invalidate();

        if (getContentHeight() > 0) {
            // WebView has displayed some content and is scrollable.
            if(listener!=null)
                listener.updateContentHeight(getContentHeight());
        }
    }



    WebViewContentHeight listener;

    public void setChangeContentListener(WebViewContentHeight listener) {
        this.listener = listener;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在片段中我试图获得内容高度

 webView.setWebChromeClient(new WebChromeClient(){
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            super.onProgressChanged(view, newProgress);
            if(newProgress==100)
            {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        webView.setChangeContentListener(new WebViewContentHeight() {
                            @Override
                            public void updateContentHeight(int height) {

                                if(height>0 && getActivity()!=null) {

                                    System.out.println("the height2 is" + height + " " + Utils.convertPixelsToDp(height, getActivity()));
                                    final int text_height = height;
Run Code Online (Sandbox Code Playgroud)

但我的问题是,我总是得到错误的结果谢谢

eya*_*nna 17

使用以下方法而不是getContentHeight()方法:

computeHorizontalScrollRange(); -> for width 
computeVerticalScrollRange(); -> for height
Run Code Online (Sandbox Code Playgroud)

这两种方法将返回整个可滚动的宽度/高度,而不是屏幕上webview的实际widht/height

  • 谢谢你,它像一个魅力 (3认同)