Gestures on Android SDK

I am working on a android project where I need to detect gestures like, fling, scroll etc.
I thought I would share on how I was able to achieve gesture detection.

 

Here are the main guts.

1. have to implement OnGestureListener (this contract will bind you to implement many methods including “onFling”)

2. You have to define a gesture detector:

 gestureDetector = new GestureDetector(this);          // initialize GestureDetector

3. That’s it now you can detect touch, fling etc.

import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;

public class SpinTheBottle extends Activity implements OnGestureListener{
....
private GestureDetector gestureDetector;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         ......
        gestureDetector = new GestureDetector(this);          // initialize GestureDetector
    }

    .....
    @Override
     public boolean onTouchEvent(final MotionEvent event){
    	          return gestureDetector.onTouchEvent(event); // bubble it up
	}

     @Override
     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		System.out.println("Fling Detected ##########################"); // terrible thing to do but for this demo, we can check the logcat to see how fling is detected
		System.out.println("e1.X: "+e1.getX() + " e1.Y: "+e1.getY()+" e2.X: "+e2.getX()+" e2.Y: "+ e2.getY());
		System.out.println("X Vel: "+ velocityX+ " Y Vel: "+ velocityY);
		return true;
	}

}
Advertisements

One thought on “Gestures on Android SDK

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s