Why is onFling() not working in ListView?

172 views Asked by At

My app
schows a ListView. When swiping right or left the ListView for a the next or previous day should be loaded.

My solution
I tried to use the onFling() methode to detect a left or right swipe. It works fine if I swipe on the TextView above the ListView.

My problem
Swiping on the ListView doesn't trigger the onFling() methode. Probably because my ListView is scrollable. Any ideas on how to solve this?

OnFling()

private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 100;
GestureDetector gestureDetector;


@Override
public boolean onTouchEvent(MotionEvent event) {
    gestureDetector.onTouchEvent(event);
    return super.onTouchEvent(event);
}

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    boolean result = false;
    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) {
            Toast.makeText(this, "Right   to Left swipe", Toast.LENGTH_SHORT).show();
            result = true;

        } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            //left to right swipe
            Toast.makeText(this, "Left to Right swipe", Toast.LENGTH_SHORT).show();
            result = true;
        }

} catch (Exception e) {
    e.printStackTrace();
}
    return result;
}
2

There are 2 answers

0
Jan Meyer On BEST ANSWER

This solved my problem:

gestureListener = new View.OnTouchListener(){
        public boolean onTouch(View v, MotionEvent event){
            return gestureDetector.onTouchEvent(event);
        }
    };

lv.setOnTouchListener(gestureListener);
1
Aaron Dunigan AtLee On

This sounds like an ideal use case for a ViewPager, which is meant for swiping left and right between different instances of the same fragment. The ViewPager handles all of the gestures for you.

See this guide and this guide for examples of how to set up a ViewPager.