1/** 2 * 手势监听 3 * 4 * @author lifengfeng 5 * 6 */ 7public class MainActivity extends Activity implements OnTouchListener, 8 OnGestureListener { 9 // 创建一个用于识别收拾的GestureDetector对象 10 @SuppressWarnings("deprecation") 11 private GestureDetector detector = new GestureDetector(this); 12 // 新建一个LinearLayout布局对象,这里是指主页面的布局 13 private LinearLayout myLayout; 14 // 限制最小移动像素 15 private int FLING_MIN_DISTANCE = 110; 16 // 定义的Toast提示框显示时间 17 private int TIME_OUT = 1000; 18 private static final String TAG = "Main"; 19 20 @Override 21 protected void onCreate(Bundle savedInstanceState) { 22 super.onCreate(savedInstanceState); 23 setContentView(R.layout.activity_main); 24 myLayout = (LinearLayout) findViewById(R.id.test_layout); 25 // 为布局绑定监听 26 myLayout.setOnTouchListener(this); 27 } 28 29 /** 30 * 手势滑动时别调用 31 */ 32 @Override 33 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, 34 float velocityY) { 35 // X轴的坐标位移大于FLING_MIN_DISTANCE,且移动速度大于FLING_MIN_VELOCITY个像素/秒 36 if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE) { 37 // 向左滑动 38 Toast.makeText(this, "向左滑动", TIME_OUT).show(); 39 } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE) { 40 // 向右滑动 41 Toast.makeText(this, "向右滑动", TIME_OUT).show(); 42 } 43 return false; 44 } 45 46 /** 47 * 长按时被调用 48 */ 49 @Override 50 public void onLongPress(MotionEvent e) { 51 Log.d(TAG, "触发长按回调"); 52 } 53 54 /** 55 * 滚动时调用 56 */ 57 @Override 58 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, 59 float distanceY) { 60 return false; 61 } 62 63 /** 64 * 在按下动作时被调用 65 */ 66 @Override 67 public boolean onDown(MotionEvent e) { 68 Log.d(TAG, "按下回调"); 69 return false; 70 } 71 72 /** 73 * 按住时被调用 74 */ 75 @Override 76 public void onShowPress(MotionEvent e) { 77 Log.d(TAG, "按住不松回调"); 78 } 79 80 /** 81 * 抬起时被调用 82 */ 83 @Override 84 public boolean onSingleTapUp(MotionEvent e) { 85 Log.d(TAG, "触发抬起回调"); 86 return false; 87 } 88 89 /** 90 * 重写OnTouchListener的onTouch方法 此方法在触摸屏被触摸,即发生触摸事件(接触和抚摸两个事件)的时候被调用 91 */ 92 @Override 93 public boolean onTouch(View v, MotionEvent event) { 94 detector.onTouchEvent(event); 95 return true; 96 } 97}
版权声明:本文为博主原创文章,未经博主允许不得转载。