Swipe Action and ViewFlipper in Android

Last tutorial I talked about ViewFlipper, in this I am just extending the functonality of ViewFlipper with swipe action. ViewFlipper is mainly used to animate views. I have two or three views added to the ViewFlipper and using the API showNext() and showPrevious(), we can show the next and previous view in the ViewFlipper. At the time of switching, we can create some animation and it looks great.

Foe switching between views, we can either use time interval or through user interaction. Last tutorial I used button for switching between Views. In this tutorial I am going to use swipe action for switching views.

class MyGestureDetector extends SimpleOnGestureListener {

  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;

  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
   System.out.println(" in onFling() :: ");
   if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
    return false;
   if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
     && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
   } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
     && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
   return super.onFling(e1, e2, velocityX, velocityY);

SWIPE_MIN_DISTANCE is used to make sure, the action is a swipe. Swipe will be valid only if we swipe upto this SWIPE_MIN_DISTANCE.
SWIPE_MAX_OFF_PATH is to make sure the swipe is almost in a straight line.

Then create an object of GestureDetector and pass our MyGestureDetector as an argument to its constructor.

GestureDetector gestureDetector;
gestureDetector = new GestureDetector(new MyGestureDetector());

Then create a OnTouchListener for flipper and attach the object of GestureDetector to it.

flipper.setOnTouchListener(new OnTouchListener() {

   public boolean onTouch(View v, MotionEvent event) {
    if (gestureDetector.onTouchEvent(event)) {
     return false;
    } else {
     return true;

Popular posts from this blog

AlarmManager and Notification in Android

Difference between SurfaceView and View in Android