Monday, October 3, 2011

How to implement Swipe action in Android

To implement swipe action in Android, such as the one used in iPhone homescreen unlock, actually Android SDK provides native support for gestures. Swipe is actually called Fling ^_^
You will need to extend SimpleOnGestureListener to implement your own handling on swipe/fling action:

class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
}

To determine if it’s a valid swipe, you will need to make sure the fling falls into an almost straight path, with at least certain length of touch duration, so it’s a continuous touch, and with certain velocity of course.
So let’s define some constants:

private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;

The max off path is to make sure the fling still falls within a somewhat straight path.
If onFling() method, you can do this:

if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
viewFlipper.setInAnimation(slideLeftIn);
viewFlipper.setOutAnimation(slideLeftOut);
viewFlipper.showNext();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
viewFlipper.setInAnimation(slideRightIn);
viewFlipper.setOutAnimation(slideRightOut);
viewFlipper.showPrevious();
}

The viewFlipper is used to show how fling/swipe make the view animation/transition from one to the other.
At last, you need to make sure in your activity, you catch the gesture event by overriding onTouch() method:

@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else
return false;
}

Here’s a screenshot of the view in transition:

Android Swipe View Flipper in Action
Android Swipe View Flipper in Action