Sobes.tech
Junior — Middle

What handler is triggered when a user performs a vertical swipe in an app?

sobes.tech AI

Answer from AI

In Android, the GestureDetector class with the GestureDetector.OnGestureListener interface implementation is usually used to handle vertical swipes. The onFling method is called during a quick finger movement (swipe). To determine a vertical swipe, the onFling method checks the direction of movement along the Y coordinate.

Example of handling a vertical swipe:

GestureDetector gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
    private static final int SWIPE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        float diffY = e2.getY() - e1.getY();
        float diffX = e2.getX() - e1.getX();
        if (Math.abs(diffY) > Math.abs(diffX)) { // vertical swipe
            if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                if (diffY > 0) {
                    // swipe down
                } else {
                    // swipe up
                }
                return true;
            }
        }
        return false;
    }
});

Thus, the onFling handler in GestureDetector with direction check is responsible for vertical swipes.

What handler is triggered when a user performs a… - sobes.tech