Target effect:
The program runs, the finger on the screen from left to right or from right to left to slide more than a certain distance, will toast output slide direction and distance.
1.activity_main.xml page to place a ImageView control.
Activity_main.xml page:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " tools:context= ". Mainactivity "> <imageview android:id=" @+id/ivshow " android:layout_width=" Match_parent " android:layout_height= "Match_parent" android:src= "@drawable/ic_launcher"/></relativelayout>
2.mainactivity.java page implementation of the sliding method. Mainactivity.java page:
Package Com.example.gesturedetector;import Android.os.bundle;import Android.app.activity;import android.util.Log; Import Android.view.gesturedetector;import Android.view.gesturedetector.simpleongesturelistener;import Android.view.menu;import Android.view.motionevent;import Android.view.view;import Android.view.view.ontouchlistener;import Android.widget.imageview;import Android.widget.toast;public Class Mainactivity extends Activity {private ImageView ivshow;private gesturedetector Gesturedetector;class Mygesturelistener extends simpleongesturelistener{@Override/* Identify the slide, the first parameter is the just start event, the second argument is the end event */public Boolean onfling ( Motionevent E1, motionevent E2, float velocityx,float velocityy) {if (E1.getx ()-e2.getx () >50) {Toast.maketext ( Mainactivity.this, "Swipe from right to left" + (E1.getx ()-e2.getx ()), Toast.length_long). Show (); else if (E2.getx ()-e1.getx () >50) {Toast.maketext (Mainactivity.this, "swipe from left to right" + (E2.getx ()-e1.getx ()), toast.length _long). Show ();} Return Super.onfling (E1, E2, Velocityx, Velocityy);}} @OverrideproteCTED void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity _main); gesturedetector=new gesturedetector (Mainactivity.this,new mygesturelistener ()); ivShow= (ImageView) Findviewbyid (r.id.ivshow); ivshow.setlongclickable (true); View must be set to true, or gesture recognition does not work correctly Ivshow.setontouchlistener (new Ontouchlistener () {/*) captures event events that occur on the touch screen */@ Overridepublic boolean OnTouch (View arg0, motionevent event) {gesturedetector.ontouchevent (event);//forwarding return false;}});}}
3. The program is relatively simple, the operation can show the target effect.
Android-gesturedetector gesture Swipe