Android sdk给我们提供了GestureDetector类,通过这个类我们可以识别很多的手势,主要是通过他的onTouchEvent(event)方法完成了不同手势的识别。
GestureDetector这个类对外提供了两个接口和一个内部类
接口:OnGestureListener,OnDoubleTapListener
内部类:SimpleOnGestureListener
SimpleOnGestureListener的方法如下:
boolean onSingleTapUp(MotionEvent e)
void onLongPress(MotionEvent e)
boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
void onShowPress(MotionEvent e)
boolean onDown(MotionEvent e)
boolean onDoubleTap(MotionEvent e)
boolean onDoubleTapEvent(MotionEvent e)
boolean onSingleTapConfirmed(MotionEvent e)
以下代码实现左滑和右滑的应用:
1 package com.cskaoyan.mobilemanager; 2 3 4 import android.app.Activity; 5 import android.os.Bundle; 6 import android.view.GestureDetector; 7 import android.view.MotionEvent; 8 import android.view.View; 9 import android.view.GestureDetector.SimpleOnGestureListener; 10 11 public abstract class SetupBaseActivity extends Activity { 12 private GestureDetector gestureDetector; 13 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 // TODO Auto-generated method stub 17 super.onCreate(savedInstanceState); 18 gestureDetector = new GestureDetector(this, new MyGestureDetectorLinstener()); 19 20 } 21 22 class MyGestureDetectorLinstener extends SimpleOnGestureListener{ 23 @Override 24 public boolean onFling( 25 MotionEvent e1, //开始滑动的那个点 26 MotionEvent e2, //滑动停止的那个点 27 float velocityX, //x方向上滑动的速度 28 float velocityY) //y方向上滑动的速度 29 { 30 // TODO Auto-generated method stub 31 float startx =e1.getX(); 32 float starty =e1.getY(); 33 float endx =e2.getX(); 34 float endy =e2.getY(); 35 36 if (endx -startx >150 ) { 37 //滑动到上一页 38 previous(); 39 System.out 40 .println("Setup1Activity.MyGestureDetectorLinstener.onFling() show previous" ); 41 } 42 else if (startx-endx>150) { 43 System.out 44 .println("Setup1Activity.MyGestureDetectorLinstener.onFling() show next" ); 45 //滑动到下一页 46 next(); 47 } 48 return super.onFling(e1, e2, velocityX, velocityY); 49 } 50 51 52 } 53 54 @Override 55 public boolean onTouchEvent(MotionEvent event) { 56 // TODO Auto-generated method stub 57 58 gestureDetector.onTouchEvent(event); 59 return super.onTouchEvent(event); 60 } 61 62 public abstract void next(); 63 public abstract void previous(); 64 }
然后抽象出两个方法next()和previous(),需要通过Fling跳转的Activity都可以继承SetupBaseActivity并实现这两个方法就OK了。