Search code examples
androidgesture

Disable up and down fling swipe gestures with GestureDetectorCompat


I'm trying to start an activity with the swipe to right or left gestures in an activity, with the following code:

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;
    }

});

How to disable the action from being taken when the swipe is vertical (from up to down or from down to up)?

The SWIPE_LEFT and SWIPE_RIGHT are nothing but class member constants with the values 1 and 2 respectively.

Thanks in advance.


Solution

  • I think you should detect high values of absVelocityY. If the value is too high, then it represents a vertical fling. In those cases don't start your new Activity.