使用GestureDetector后,单击或选择内部WebView无法正常工作

问题描述 投票:0回答:1

我在片段中使用webView,具有以下设置 -

webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.canGoBackOrForward(0);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.clearCache(true);

我在这个webView中加载的网页需要javascript,即点击网页内的按钮确实有些功能。它确实有效,如果我使用上面提到的那样。但我也希望webView检测Gesture像向左/向右滑动,所以我尝试使用GestureDetector如下 -

final GestureDetector gesture = new GestureDetector(getActivity(),
new GestureDetector.SimpleOnGestureListener() {

    @Override
    public boolean onDown(MotionEvent e) {
        Log.d(LOGCAT, "onDown from gesture");
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {
        Log.d(LOGCAT, "onFling has been called!");
        final int SWIPE_MIN_DISTANCE = 120;
        final int SWIPE_MAX_OFF_PATH = 250;
        final int SWIPE_THRESHOLD_VELOCITY = 200;
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.d(LOGCAT, "Right to Left");
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.d(LOGCAT, "Left to Right");
            }
        } catch (Exception e) {
            // nothing
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }
});

webView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gesture.onTouchEvent(event);
    }
});

这个GestureDetector,确实检测到右/左滑动,但现在正常点击webView内部不起作用,这是javascript在加载的网页内工作所必需的。

那么,如何使两者(javascript和GestureDetector的正常点击检测)同时工作?

android webview swipe gesture
1个回答
0
投票

根据this answer,替换:

webView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gesture.onTouchEvent(event);
    }
});

有:

webView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        gesture.onTouchEvent(event);
        return v.onTouchEvent(event);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.