【问题标题】:Getting WebView Content height once its loaded Android加载Android后获取WebView内容高度
【发布时间】:2016-03-29 10:36:03
【问题描述】:

我正在尝试根据其内容高度在 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 必须在可运行对象中吗?如果我们只是设置没有它的侦听器,我们不能得到一个准确的值吗?

标签: android html webview


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢你,它就像一个魅力
  • 非常感谢,很好的回答!
  • 结合使用 onScrolledSchanged() 可以更有效地处理顶部和底部。
  • 这些方法是针对scrollview的,问题是针对webview的。我的情况是只需要 webview 的高度,而不是整个滚动视图
  • @Siavash 垂直滚动范围其实就是webview的高度
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多