我在片段中使用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
的正常点击检测)同时工作?
根据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);
}
});