最近在進行混合開發(fā)過程中,用viewpager+fragment的方式在基本框架,在里面fragment中包含webview,而在webview中存在一個橫屏輪播的控件,導(dǎo)致在執(zhí)行webview輪播滑動時,會觸發(fā)viewpager的滑動,導(dǎo)致webview的輪播失效,經(jīng)過一番對該問題的搜索和實踐,最后將問題解決。該方法需要網(wǎng)頁與Android兩端配合使用。
解決的方法:
首先需要在網(wǎng)頁端寫js接口,獲取輪播控件的寬高以及相對于原點的位置,獲取輪播寬高的坐標(biāo)的實際也比較重要,需要在頁面剛加載獲取一次,現(xiàn)在輪播控件的寬高,并且調(diào)起寫好的js調(diào)Android的方法,同時也需要Android端定義好對應(yīng)的接口,并且在上下滑動的時候也需要去計算現(xiàn)在輪播控件的寬高,并且給Android端發(fā)送過去。
由于我主要開發(fā)的Android端,所以不知道網(wǎng)頁端js的代碼,如有需要自行查找:
window.onload = function(){ ... } window.onscroll = function(){ ... }在Android端的主要代碼:
首先需要定義一個類來接收js接口返回的坐標(biāo)值
public class PagerDesc {    PRivate int top;    private int left;    private int right;    private int bottom;    //get set方法    public PagerDesc(int top, int left, int right, int bottom) {        this.top = top;        this.bottom = bottom;    }}定義js接口,用PagerDesc類來接收返回的原點坐標(biāo)和寬高值當(dāng)解決完以上的內(nèi)容,接下來是根據(jù)Android的機制來進行在webview的onTouch事件進行處理
詳細(xì)代碼:
webView.setOnTouchListener(new View.OnTouchListener() {                @Override                public boolean onTouch(View v, MotionEvent event) {                    //獲取y軸坐標(biāo)                    float y = event.getRawY();                    switch (event.getAction()) {                        case MotionEvent.ACTION_DOWN:                            if (null != mPagerDesc) {                                int top = mPagerDesc.getTop();                                int bottom = top + (mPagerDesc.getBottom() - mPagerDesc.getTop());                                //將CSS像素轉(zhuǎn)換為android設(shè)備像素并考慮通知欄高度                                DisplayMetrics metric = context.getResources().getDisplayMetrics();                                top = (int) (top * metric.density) + ScreenUtil.getStatusBarHeight(getActivity());                                bottom = (int) (bottom * metric.density) + ScreenUtil.getStatusBarHeight(getActivity());                                //如果觸摸點的坐標(biāo)在輪播區(qū)域內(nèi),則由webview來處理事件,否則由viewpager來處理                                if (y > top&& y<bottom){                                    webView.requestDisallowInterceptTouchEvent(true);                                }else{                                    webView.requestDisallowInterceptTouchEvent(false);                                }                            } break;                        case MotionEvent.ACTION_UP:                            break;                        case MotionEvent.ACTION_MOVE:                            break;                    }                    return false;                }            });這樣基本就可以了。
新聞熱點
疑難解答
圖片精選