继承SimpleOnGestureListener 类,判断左右滑动并处理事件:
class MyGestureDetector extends SimpleOnGestureListener {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if(CommonUtil.DEBUG)Log.i("test ", "left");
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if(CommonUtil.DEBUG)Log.i("test ", "right");
}
} catch (Exception e) {
Log.e(TAG, "onFling error", e);
}
return false;
}
}
在activity中定义GestureDetector 变量
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
在oncreate()中赋值:
gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
};
重写dispatchTouchEvent(MotionEvent event)方法
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
event.setAction(MotionEvent.ACTION_CANCEL);
}
return super.dispatchTouchEvent(event);
}