在Android中加载WebView内容后获取其高度

7

我正在尝试在基于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;
    }
}

然后在片段中我尝试获取内容的高度

 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;

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

你能解释一下为什么ContentListener必须在可运行状态下吗?如果我们没有它,我们不能得到准确的值吗? - Teffi
1个回答

18

请使用以下方法代替getContentHeight() 方法:

computeHorizontalScrollRange(); -> for width 
computeVerticalScrollRange(); -> for height

这两种方法将返回可滚动的宽度/高度,而不是Webview在屏幕上实际的宽度/高度


3
谢谢,它完美地运行了。 - Antwan
非常感谢,回答得很好! - dees91
使用onScrolledSchanged()的组合可以更有效地处理顶部和底部。 - Abhishek
1
这些方法适用于ScrollView,而问题是针对WebView提出的。我处于需要仅获取WebView高度而不是整个ScrollView的情况下。 - Siavash
@Siavash,垂直滚动范围实际上是Web视图的高度。 - eyadMhanna
找不到这些方法?如何使用它们?WebView 没有这样的方法。 - mcfly soft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接