如何获取WebView内容高度

序言

最近项目需求中需要实现WebView显示内容,下方显示评论列表,列表还可以分页加载。我最近做了技术预研,难度主要是实时获取WebView的高度。

效果

1.分页加载

这里写图片描述

2.动态获取高度,点击阅读更多,会将几个隐藏的div,显示出来,造成WebView内容高度变化。

这里写图片描述

实现

使用的ScrollView包裹一层LinearLayout,LinearLayout中依次防止WebView和RecyclerView。布局如下:

<?xml version="1.0" encoding="utf-8"?>
<com.trs.studyview.view.TRSScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.trs.studyview.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <com.trs.studyview.view.TRSWebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="100dp" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

</com.trs.studyview.view.TRSScrollView>

问题一,如果获取WebView高度

1.通过js获取

以下是js获取高度的方法

网页可见区域宽: document.body.clientWidth 
网页可见区域高: document.body.clientHeight 
网页可见区域宽: document.body.offsetWidth (包括边线的宽) 
网页可见区域高: document.body.offsetHeight (包括边线的高) 
网页正文全文宽: document.body.scrollWidth 
网页正文全文高: document.body.scrollHeight 
网页被卷去的高: document.body.scrollTop 
网页被卷去的左: document.body.scrollLeft 
网页正文部分上: window.screenTop 
网页正文部分左: window.screenLeft 
屏幕分辨率的高: window.screen.height 
屏幕分辨率的宽: window.screen.width 
屏幕可用工作区高度: window.screen.availHeight 
屏幕可用工作区宽度: window.screen.availWidth 

下面是测试代码

package com.trs.studyview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.trs.studyview.adpater.CommentAdapter;
import com.trs.studyview.view.TRSScrollView;
import com.trs.studyview.view.TRSWebView;

public class MainActivity extends AppCompatActivity {
    TRSWebView webView;
    RecyclerView recyclerView;
    String url = "http://app.nxnews.net/ningxia/cfwz/zt/201708/t20170807_1859270.html";
    CommentAdapter adapter;
    TRSScrollView scrollView;
    Mobile mobile = new Mobile();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }


    private void initView() {
        scrollView = $(R.id.scrollView);
        webView = $(R.id.webview);
        recyclerView = $(R.id.recyclerView);
        WebSettings setting = webView.getSettings();
        setting.setJavaScriptEnabled(true);//支持js
        webView.addJavascriptInterface(mobile, "mobile");
        webView.setWebViewClient(mClient);
        webView.loadUrl(url);
        adapter = new CommentAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        scrollView.setRecyclerView(recyclerView);
    }

    private class Mobile {
        @JavascriptInterface
        public void onGetWebContentHeight(String type, int height) {
            Log.i("zzz", "onGetWebContentHeight type=" + type + " height=" + height);

        }
    }

    private String[] getHeightJs = new String[]{
            "document.body.clientHeight",
            "document.body.offsetHeight",
            "document.body.scrollHeight",
            "document.body.scrollTop",
            "window.screen.availHeight"
    };

    private WebViewClient mClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            for (int i = 0; i < getHeightJs.length; i++) {
                String js = "javascript:mobile.onGetWebContentHeight(\"" + getHeightJs[i] + "\"," + getHeightJs[i] + ")";
                view.loadUrl(js);
            }
        }
    };

    protected <T extends View> T $(int id) {
        return (T) findViewById(id);
    }
}

结果如下:

这里写图片描述

可以告诉大家以上高度都不对。

2.通过getContentHeight()获取高度

思路是在网页加载完成以后通过WebView的getContentHeight()方法获取高度
代码如下:

    private WebViewClient mClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            Log.i("zzz", "webview contentHeight=" + view.getContentHeight());
        }
    };

运行结果

这里写图片描述

结论:高度不对

3.通过measure()进行测量

思路,在WebView加载网页完毕以后,通过webview.measure(0,0)进行测量,两个0表示对宽高无限制。

代码改动部分


    private class Mobile {
        @JavascriptInterface
        public void onGetWebContentHeight() {
            //重新调整webview高度
            webView.post(() -> {
                webView.measure(0, 0);
                int measuredHeight = webView.getMeasuredHeight();
                Log.i("zzz", "measuredHeight=" + measuredHeight);
            });


        }
    }


    private WebViewClient mClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            mobile.onGetWebContentHeight();
        }
    };

运行结果

这里写图片描述

结论:大家可以看到这个高度是最高的,也的确是webView网页内容的高度。

总结

至此大家以后就知道怎么获取WebView内容高度了

问题二,如果监听网页高度变化

这是第一次打开APP的时候,获取到网页高度,在重新设置webView的高度,和RecyclerView的高度
代码如下


    private class Mobile {
        @JavascriptInterface
        public void onGetWebContentHeight() {
            //重新调整webview高度
            webView.post(() -> {
                webView.measure(0, 0);
                int measuredHeight = webView.getMeasuredHeight();
                ViewGroup.LayoutParams layoutParams = webView.getLayoutParams();
                layoutParams.height = measuredHeight;
                webView.setLayoutParams(layoutParams);
                ViewGroup.LayoutParams layoutParams1 = recyclerView.getLayoutParams();
                layoutParams1.height = scrollView.getHeight();
                Log.i("zzz", "scrollView height=" + scrollView.getHeight());
                recyclerView.setLayoutParams(layoutParams1);
            });


        }
    }


    private WebViewClient mClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            mobile.onGetWebContentHeight();
        }
    };

效果如下:可以看到网页全部显示了,这已经滑动到网页的最底部。

这里写图片描述

但问题是点击阅读更多,网页中有几个隐藏的新闻被显示出来,造成网页内容高度变化,但是我们检测不到网页内容高度变化,所以变成这样了。

这里写图片描述

下面是我的解决思路。

思路1.通过js监听内容变化

我通过设置window的resize监听来实现高度变化的监听。下面使用浏览器来测试:

这里写图片描述

结果点击阅读更多,没有触发相关的函数。只有调整window大学的时候才会


这里写图片描述

思路2.在WebView的onDraw方法中监听

经过我的实验在点击阅读更多以后webView的contentHeight会发生变化,于是我就扩展了WebView使其能监听内容高度变化

这是我的自定义WebView:

package com.trs.studyview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.WebView;

/**
 * Created by zhuguohui on 2017/8/8.
 */

public class TRSWebView extends WebView {
    private int lastContentHeight = 0;
    private static final int MSG_CONTENT_CHANGE = 1;
    private onContentChangeListener onContentChangeListener = null;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CONTENT_CHANGE:
                    if (onContentChangeListener != null) {
                        onContentChangeListener.onContentChange();
                    }
                    break;
            }
        }
    };


    public TRSWebView(Context context) {
        this(context, null);
    }

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

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (getContentHeight() != lastContentHeight) {
            handler.sendEmptyMessage(MSG_CONTENT_CHANGE);
            lastContentHeight = getContentHeight();
            Log.i("www", "contentChange height=" + getContentHeight());
        }

    }

    public void setOnContentChangeListener(TRSWebView.onContentChangeListener onContentChangeListener) {
        this.onContentChangeListener = onContentChangeListener;
    }

    /**
     * 监听内容高度发生变化
     */
    public interface onContentChangeListener {
        void onContentChange();
    }
}

点击多次阅读更多

这里写图片描述

结论:可以监听网页内容的变化

问题三 recyclerView的滑动冲突。

我是通过自定义ScrollView来实现的,具体代码如下,测试可用

package com.trs.studyview.view;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * Created by zhuguohui on 2017/8/8.
 */

public class TRSScrollView extends ScrollView {
    RecyclerView recyclerView;

    public TRSScrollView(Context context) {
        this(context, null);
    }

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


    public void setRecyclerView(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    int downY;
    int moveY = 0;
    MotionEvent downEvent;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //如果RecyclerView
        if (recyclerView != null) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downEvent = ev;
                    downY = (int) ev.getX();
                    moveY = 0;
                    break;
                case MotionEvent.ACTION_MOVE:
                    int moveY = (int) ev.getY() - downY;
                    if (Math.abs(moveY) > 20) {
                        //表示滑动
                        if (moveY > 0) {
                            //向下滑动,如果recyclerView还没有显示则拦截事件
                            if (getScrollY() < recyclerView.getTop()) {
                                return true;
                            }
                        } else {
                            //向上滑动
                            if (getScrollY() == recyclerView.getTop()) {
                                //如果第一个item已经显现才拦截事件
                                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                                if (layoutManager.findFirstVisibleItemPosition() == 0) {
                                    return true;
                                }
                            }
                        }
                    }
                    break;
            }
        }

        return super.onInterceptTouchEvent(ev);
    }
}

最终运行代码

package com.trs.studyview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.trs.studyview.adpater.CommentAdapter;
import com.trs.studyview.view.TRSScrollView;
import com.trs.studyview.view.TRSWebView;

public class MainActivity extends AppCompatActivity {
    TRSWebView webView;
    RecyclerView recyclerView;
    String url = "http://app.nxnews.net/ningxia/cfwz/zt/201708/t20170807_1859270.html";
    CommentAdapter adapter;
    TRSScrollView scrollView;
    Mobile mobile = new Mobile();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }


    private void initView() {
        scrollView = $(R.id.scrollView);
        webView = $(R.id.webview);
        recyclerView = $(R.id.recyclerView);
        WebSettings setting = webView.getSettings();
        setting.setJavaScriptEnabled(true);//支持js
        webView.addJavascriptInterface(mobile, "mobile");
        // webView.setWebViewClient(mClient);
        webView.setOnContentChangeListener(() -> {
            mobile.onGetWebContentHeight();
        });
        webView.loadUrl(url);
        adapter = new CommentAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        scrollView.setRecyclerView(recyclerView);
    }

    private class Mobile {
        @JavascriptInterface
        public void onGetWebContentHeight() {
            //重新调整webview高度
            webView.post(() -> {
                webView.measure(0, 0);
                int measuredHeight = webView.getMeasuredHeight();
                ViewGroup.LayoutParams layoutParams = webView.getLayoutParams();
                layoutParams.height = measuredHeight;
                webView.setLayoutParams(layoutParams);
                ViewGroup.LayoutParams layoutParams1 = recyclerView.getLayoutParams();
                layoutParams1.height = scrollView.getHeight();
                Log.i("zzz", "scrollView height=" + scrollView.getHeight());
                recyclerView.setLayoutParams(layoutParams1);
            });

        }
    }

    private WebViewClient mClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
        }
    };

    protected <T extends View> T $(int id) {
        return (T) findViewById(id);
    }
}

总结

这个需求难度在于知识的广度,例如对JavaScript的熟悉程度,对View事件拦截的理解。研究的过程很有趣,克服重重困难,完成任务的感觉很不错的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容