Share the post "How To Fling Up, Down, Left, Right In Android Using GestureDetector"
Here is an effective class I use to detect gestures in Android devices such as flinging in any direction whether it is up, down, left or right using a GestureDetector.
I found this class in the illusionsandroid website and modified it a little to suit my requirements such as changing the value to at least detect a bit of a long fling rather than a short one.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
public class OnFlingGestureListener implements OnTouchListener { private GestureDetector gdt; @Override public boolean onTouch(View v, MotionEvent event) { if (gdt == null) gdt = new GestureDetector(v.getContext(), new GestureListener()); return gdt.onTouchEvent(event); } private final class GestureListener extends SimpleOnGestureListener { private static final int SWIPE_MIN_DISTANCE = 150; private static final int SWIPE_THRESHOLD_VELOCITY = 100; @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { onRightToLeft(); return true; } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { onLeftToRight(); return true; } if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { onBottomToTop(); return true; } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { onTopToBottom(); return true; } return false; } } public void onRightToLeft() { } public void onLeftToRight() { } public void onBottomToTop() { } public void onTopToBottom() { } } |
To use the class. do it like this.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
OnFlingGestureListener flingListener = new OnFlingGestureListener() { @Override public void onRightToLeft() { } @Override public void onLeftToRight() { } @Override public void onTopToBottom() { } @Override public void onBottomToTop() { } }; |
And, in your onTouch() method as I am sure your Activity implements the OnTouchListener, use the flingListener like this:
|
1 2 3 4 5 6 7 8 9 10 11 |
@Override public boolean onTouch(View view, MotionEvent me) { if (flingListener.onTouch(view, me)) { // if gesture detected, ignore other touch events return false; } if (me.getAction() == MotionEvent.ACTION_DOWN) { // normal touch events } } |