Step 1: 初始化手势组件
detector = new GestureDetector(this, onGestureListener);
Step 2: 手势组件添加监听,为了方便各处使用,因此将监听事件独立出来了,用到的地方只需重写一下抽象方法即可
package com.example.demo.weimuyundemo.plugins.gesturedetector;
import android.view.GestureDetector;
import android.view.MotionEvent;
public abstract class CustomGestureDetectorListener implements GestureDetector.OnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public abstract boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
}
Step 3: 为webView添加touch监听
x5WebView.setOnTouchListener(this);
Step 4: 重写activity onTouch方法,绑定手势onTouch事件
@Override
public boolean onTouch(View v, MotionEvent event) {
return detector.onTouchEvent(event);
}
Step 5: 重写手势监听的抽象方法,待Step 1使用
private CustomGestureDetectorListener onGestureListener = new CustomGestureDetectorListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float x = e2.getX() - e1.getX();
float y = e2.getY() - e1.getY();
judgeSwiperDirection(x,y);
return true;
}
};
/**
* 判断左滑右滑
* @param xAxis X轴滑动距离
* @param yAxis Y轴滑动距离
*/
private void judgeSwiperDirection (float xAxis, float yAxis) {
boolean isYInControlled = Math.abs(yAxis) <= 100;
if (isYInControlled) {
if (xAxis > 25) {
Log.i("TAG", "右滑触发");
if (null != x5WebView && x5WebView.canGoForward()) {
x5WebView.goForward();
}
} else if (xAxis < -25) {
Log.i("TAG", "左滑触发");
if (null != x5WebView && x5WebView.canGoBack()) {
x5WebView.goBack();
} else {
Log.i("TAG", "手势返回到主页面");
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
this.finish();
}
}
}
}
Tip:
说明下,写这篇文章的时候是根据实际的业务需要些的,文章中是要给webview添加左滑右滑的,使用的是腾讯X5内核。因为只考虑左滑右滑,因此当上下滑动距离超过100的时候,就过滤掉了。