1. 程式人生 > >如何獲取WebView內容高度

如何獲取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事件攔截的理解。研究的過程很有趣,克服重重困難,完成任務的感覺很不錯的。