我正在尝试使用以下代码在活动中向右或向左滑动手势来启动活动:
gestureDetector = new GestureDetectorCompat(this, new GestureDetector.SimpleOnGestureListener(){
private static final int SWIPE_THRESHOLD = 50;
private static final int SWIPE_VELOCITY_THRESHOLD = 0;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
//user will move forward through messages on fling up or left
boolean forward = false;
//user will move backward through messages on fling down or right
boolean backward = false;
//calculate the change in X position within the fling gesture
float horizontalDiff = event2.getX() - event1.getX();
//calculate the change in Y position within the fling gesture
float verticalDiff = event2.getY() - event1.getY();
float absHDiff = Math.abs(horizontalDiff);
float absVDiff = Math.abs(verticalDiff);
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(velocityY);
if(absHDiff > absVDiff && absHDiff > SWIPE_THRESHOLD && absVelocityX > SWIPE_VELOCITY_THRESHOLD){
//move forward or backward
if(horizontalDiff>0) backward=true;
else forward=true;
}
else if(absVDiff > SWIPE_THRESHOLD && absVelocityY > SWIPE_VELOCITY_THRESHOLD){
if(verticalDiff>0) backward=true;
else forward=true;
}
//user is cycling forward through messages
if(forward){
//check current message is not at end of array, increment or set back to start
swipeTo(SWIPE_LEFT);
}
//user is cycling backwards through messages
else if(backward){
//check that current message is not at start of array, decrement or set to last message
swipeTo(SWIPE_RIGHT);
}
//return super.onFling(event1, event2, velocityX, velocityY);
return true;
}
});
如何在滑动垂直(从上到下或从下到上)时禁用操作?
SWIPE_LEFT和SWIPE_RIGHT只是类成员常量,值分别为1和2。
提前致谢。
答案 0 :(得分:0)
我认为你应该检测到absVelocityY
的高值。如果该值太高,则表示垂直投掷。在这些情况下,请勿启动新的Activity
。