Recently I wanted to implement swipe functionality for activity in my android app but couldn't find a nice and simple example that would explain what do you really need to do. There are multiple sites that are bloated with code, but somehow I couldn't believe that to implement such a simple (and kinda basic if you think about it) functionality you need to write tens of lines of code.
So if you're like me, looking for a simple and elegant solution for swipe gesture handling, here it is...
First some theory - to implement swipe you will need to:
1. Create a GestureDetector
2. Create an OnGestureListener by extending GestureDetector.SimpleOnGestureListener
3. Implement onFling method in listener created in step 2
4. Handle the onTouchEvent in your activity
Now let's jump to the code:
That's it. Enjoy your swipe-enabled activity :)
So if you're like me, looking for a simple and elegant solution for swipe gesture handling, here it is...
First some theory - to implement swipe you will need to:
1. Create a GestureDetector
2. Create an OnGestureListener by extending GestureDetector.SimpleOnGestureListener
3. Implement onFling method in listener created in step 2
4. Handle the onTouchEvent in your activity
Now let's jump to the code:
import android.app.Activity; import android.os.Bundle; import android.view.GestureDetector; import android.view.MotionEvent; public class MySwipeSupportedActivity extends Activity { // swipe gesture constants private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private GestureDetector gestureDetector; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gestureDetector = new GestureDetector(this, new OnSwipeGestureListener()); // TODO: any other logic you require in the onCreate } @Override public boolean onTouchEvent(MotionEvent event) { return gestureDetector.onTouchEvent(event); } /** * Class handling swipe gesture */ private class OnSwipeGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { float deltaX = e2.getX() - e1.getX(); if ((Math.abs(deltaX) < SWIPE_MIN_DISTANCE) || (Math.abs(velocityX) < SWIPE_THRESHOLD_VELOCITY)) { return false; // insignificant swipe } else { if (deltaX < 0) { // left to right handleSwipeLeftToRight(); } else { // right to left handleSwipeRightToLeft(); } } return true; } } private void handleSwipeLeftToRight() { // TODO: implement the business logic here } private void handleSwipeRightToLeft() { // TODO: implement the business logic here } }
That's it. Enjoy your swipe-enabled activity :)
Nice post...very helpful !!!!
ReplyDeleteGreat!
ReplyDeleteThis is the most simple way of doing this that I have seen...