Friday, 22 August 2014

Using GestureDetector in Android ImageView

I've found quite a few discussions on the Internet with regards to using GestureDetector for your ImageView; some of them are more useful than the others. The bottom line is: there are two ways of doing this:

  • Either subclassing ImageView and using newly created view in your activity XML file
  • Or simply delegating all events from ImageView to the gesture detector in your activity.
In fact, second way is extremely simple, so I want to share with you an example of how this can be done.


public class ShowImageActivity extends Activity {

  private static final String TAG = ShowImageActivity.class.getSimpleName();

  class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
    @Override
    public void onLongPress(MotionEvent e) {
      Log.d(TAG, "onLongPress " + e.toString());
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
      Log.d(TAG, "onSingleTapConfirmed " + e.toString());
      return true;
    }

    // You really need all these boilerplate methods for GestureDetector to work

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
      return true;
    }
    @Override
    public boolean onDown(MotionEvent e) {
      return true;
    }
  }