Monday, October 5, 2009

Gesture Detection on Android

I just got my gesture detection code working. It's a fun way and a convenient way as well to enhance the usability of your application. So, here is the code that gets you going. First, for the Activity that you want to detect gestures, the OnGestureListener interface has to be implemented. Then, you need to override the methods and implement them. And finally, you need to implement the onTouchEvent method of the activity that will trigger the gesture listener code.

   1: package com.beanie.androidco;
   2:  
   3: import android.app.Activity;
   4: import android.os.Bundle;
   5: import android.view.GestureDetector;
   6: import android.view.MotionEvent;
   7: import android.view.GestureDetector.OnGestureListener;
   8:  
   9: public class GestureDemo extends Activity implements OnGestureListener {
  10:     private GestureDetector gestureDetector;
  11:     @Override
  12:     public void onCreate(Bundle savedInstanceState) {
  13:         super.onCreate(savedInstanceState);
  14:         setContentView(R.layout.main);
  15:         gestureDetector = new GestureDetector(this);
  16:     }
  17:  
  18:     @Override
  19:     public boolean onTouchEvent(MotionEvent event) {
  20:         return gestureDetector.onTouchEvent(event);
  21:     }
  22:  
  23:     @Override
  24:     public boolean onDown(MotionEvent e) {
  25:         // Do something
  26:         return false;
  27:     }
  28:  
  29:     @Override
  30:     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
  31:             float velocityY) {
  32:         // Do something
  33:         return false;
  34:     }
  35:  
  36:     @Override
  37:     public void onLongPress(MotionEvent e) { 
  38:         // Do something
  39:     }
  40:  
  41:     @Override
  42:     public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
  43:             float distanceY) {
  44:         // Do something
  45:         return false;
  46:     }
  47:  
  48:     @Override
  49:     public void onShowPress(MotionEvent e) { 
  50:         // Do something
  51:     }
  52:  
  53:     @Override
  54:     public boolean onSingleTapUp(MotionEvent e) { 
  55:         // Do something 
  56:         return false;
  57:     }
  58: }

The most commonly used method would probably be the onFling method, where you have to check for a threshold velocity and displacement before you would want to trigger an action. For detecting Left Fling, Right Fling, Scroll down/up, you will need to write some extra code in the corresponding methods. Enjoy...