码迷,mamicode.com
首页 > 移动开发 > 详细

Android手势监听

时间:2015-09-01 16:33:29      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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;
        }
    }
}

 

Android手势监听

标签:

原文地址:http://www.cnblogs.com/hunhunee/p/4775889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!