标签:
public class MainActivity extends Activity { /* * 要实现手指在屏幕上左右滑动的事件需要实例化对象GestureDetector,new * GestureDetector(MainActivity.this * ,onGestureListener);首先实现监听对象GestureDetector * .OnGestureListener,根据x或y轴前后变化坐标来判断是左滑动还是右滑动并根据不同手势滑动做出事件处理doResult(int * action), * * 然后覆写onTouchEvent方法,在onTouchEvent方法中将event对象传给gestureDetector.onTouchEvent( * event);处理。 */ private GestureDetector gestureDetector; final int TOP = 1, BOTTOM = 2, LEFT = 3, RIGHT = 4; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println("执行"); gestureDetector = new GestureDetector(this, myListener); } private GestureDetector.OnGestureListener myListener = new GestureDetector.SimpleOnGestureListener() { public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { float xExcursion = e1.getX() - e2.getX(); float yExcursion = e1.getY() - e2.getY(); if (yExcursion > 0 && Math.abs(yExcursion) > Math.abs(xExcursion)) { executeAction(TOP); } else if (yExcursion < 0 && Math.abs(yExcursion) > Math.abs(xExcursion)) { executeAction(BOTTOM); } else if (xExcursion > 0 && Math.abs(xExcursion) > Math.abs(yExcursion)) { executeAction(LEFT); } else { executeAction(RIGHT); } return true; } }; public boolean onTouchEvent(MotionEvent event) { return gestureDetector.onTouchEvent(event); } public void executeAction(int action) { switch (action) { case 1: Toast.makeText(this, "上", Toast.LENGTH_SHORT).show(); break; case 2: Toast.makeText(this, "下", Toast.LENGTH_SHORT).show(); break; case 3: Toast.makeText(this, "左", Toast.LENGTH_SHORT).show(); break; case 4: Toast.makeText(this, "右", Toast.LENGTH_SHORT).show(); break; default: break; } } }
标签:
原文地址:http://www.cnblogs.com/hunhunee/p/4775889.html