在Webview上设置一个OnTouchListener,检测用户手指的移动方向。然后禁用父view的滑动事件,使得可以在Webview上进行滚动操作,并尽可能去维持Webview的默认行为。
示例代码:
webView.setOnTouchListener(new View.OnTouchListener() {
private float pointX, pointY;
private int tolerance = 50;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
pointX = event.getX();
pointY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
float deltaX = Math.abs(pointX - event.getX());
float deltaY = Math.abs(pointY - event.getY());
if (deltaX > deltaY && deltaX > tolerance) {
// 水平方向移动,禁止父view滚动
v.getParent().requestDisallowInterceptTouchEvent(true);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// 恢复父view的滑动事件拦截
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return false;
}
});