android onTouchEvent 左右手势滑动事件处理

来源:互联网 发布:新浪集团网络运营 编辑:程序博客网 时间:2024/05/16 09:05

要实现手指在屏幕上左右滑动的事件需要实例化对象GestureDetector,new GestureDetector(MainActivity.this,onGestureListener);首先实现监听对象GestureDetector.OnGestureListener,根据x或y轴前后变化坐标来判断是左滑动还是右滑动并根据不同手势滑动做出事件处理doResult(int action),然后覆写onTouchEvent方法,在onTouchEvent方法中将event对象传给gestureDetector.onTouchEvent(event);处理。

 

MainActivity.java

[java] view plaincopy
  1. import android.view.GestureDetector;  
  2.   
  3. public MainActivity extends TabActivity implements OnClickListener {  
  4.   
  5.     final int RIGHT = 0;  
  6.     final int LEFT = 1;  
  7.     private GestureDetector gestureDetector;  
  8.   
  9.     /** Called when the activity is first created. */  
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.main);  
  15.   
  16.         gestureDetector = new GestureDetector(MainActivity.this,onGestureListener);  
  17.     }  
  18.   
  19.     private GestureDetector.OnGestureListener onGestureListener =   
  20.         new GestureDetector.SimpleOnGestureListener() {  
  21.         @Override  
  22.         public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,  
  23.                 float velocityY) {  
  24.             float x = e2.getX() - e1.getX();  
  25.             float y = e2.getY() - e1.getY();  
  26.   
  27.             if (x > 0) {  
  28.                 doResult(RIGHT);  
  29.             } else if (x < 0) {  
  30.                 doResult(LEFT);  
  31.             }  
  32.             return true;  
  33.         }  
  34.     };  
  35.   
  36.     public boolean onTouchEvent(MotionEvent event) {  
  37.         return gestureDetector.onTouchEvent(event);  
  38.     }  
  39.   
  40.     public void doResult(int action) {  
  41.   
  42.         switch (action) {  
  43.         case RIGHT:  
  44.             System.out.println("go right");  
  45.             break;  
  46.   
  47.         case LEFT:  
  48.             System.out.println("go right");  
  49.             break;  
  50.   
  51.         }  
  52.     }  
  53. }  

 参考http://www.cnblogs.com/meieiem/archive/2011/09/16/2178313.html
0 0