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