Thursday 11 August 2011

Android: handling gestures

The basics of detecting and handling gestures is a three step process follows:
(1) Add a GestureDetector instance to your Activity or View (as appropriate), e.g.

private GestureDetector gestureDetector;

(2) Instantiate it somewhere, the Activity's onCreate(...) method perhaps:

gestureDetector = new GestureDetector(MyActivity.this, new SimpleOnGestureListener()
{
@Override
public boolean onDown(MotionEvent e)
{
 return true;
}

 @Override
 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
 { /* do something */ }
});

(3) Override the Activity's onTouchEvent(...) method:

@Override
public boolean onTouchEvent(MotionEvent event)
{
 if (gestureDetector != null) return gestureDetector.onTouchEvent(event);
 else return super.onTouchEvent(event);
}

That's it. That's the basics. See comments for some extra niceties.

2 comments:

adil said...

Here's the code to put in the onFling(...) method to detect and act on right-to-left and left-to-right swipes...

try
{
// ignore swipe since it's not quite horizontal
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)
{
/* do something */
return true;
}

// left to right swipe
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
/* do something */
return true;
}
}
catch (Exception ex) { /* nothing */ }

return false;
}


... where you'll need to define the following in your Activity or somewhere...

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;

adil said...

If you want to detect gestures on a particular View within the Activity only and not the whole Activity, then, instead of overriding the Activity's onTouchEvent(...) method, you'll need attach an OnTouchListener to your View as follows:

myView.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
if (gestureDetector != null)
return gestureDetector.onTouchEvent(event);

else return false;
}
});