When using Android phones, you will often encounter a lot of applications that do a great job, such as sliding your fingers to the left or right of the screen to switch the interface. This actually uses a gesturedetector object gesture: gesture-making gesture, detector: monitoring the detector. In fact, it is to determine the next action by calculating the XY axis displacement from the screen to the screen, and the moving speed.
There are three steps to implement a sliding listener (click, double-click, long-press, and so on) for a widget in gesture recognition: 1. Create a defaultgesturedetector class that inherits from the simpleongesturelistener override onfling event 2. instantiate a gesture recognition object gesturedetector GD = new gestruedetector (new feature (); 3. Override the ontouchevent () event (activity override directly, the control is setontouchlistener ())
Step 1:
Class defaultgesturedetector extends simpleongesturelistener {
@ Override
Public Boolean onfling (motionevent E1, motionevent E2, float velocityx, float velocityy ){
Final int fling_min_distance = 100; // The distance between the X and Y axes (in pixels)
Final int fling_min_velocity = 200; // The movement speed on X or Y axis (pixel/second)
If (e1.getx ()-e2.getx ()> fling_min_distance & math. Abs (velocityx)> fling_min_velocity)
Toast. maketext (main. This, "Slide left", Toast. length_short). Show ();
Else if (e2.getx ()-e1.getx ()> fling_min_distance & math. Abs (velocityx)> fling_min_velocity)
Toast. maketext (main. This, "slide to the right", Toast. length_short). Show ();
Return false;
}
}
The above e1.getx ()-e2.getx () is the moving speed from the X axis to the velocityx: the X axis.
Part 2:
private GestureDetector gestureDetector;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector=new GestureDetector(new DefaultGestureDetector());
}
Part III:
@Override
public boolean onTouchEvent(MotionEvent event){
return gestureDetector.onTouchEvent(event);
}