How to distinguish between move and click in onTouchEvent()?

后端 未结 10 2136
暖寄归人
暖寄归人 2020-11-28 22:30

In my application, I need to handle both move and click events.

A click is a sequence of one ACTION_DOWN action, several ACTION_MOVE actions and one ACTION_UP action

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 23:29

    Using Gil SH answer, I improved it by implementing onSingleTapUp() rather than onSingleTapConfirmed(). It is much faster and won't click the view if dragged/moved.

    GestureTap:

    public class GestureTap extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            button.performClick();
            return true;
        }
    }
    

    Use it like:

    final GestureDetector gestureDetector = new GestureDetector(getApplicationContext(), new GestureTap());
    button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            gestureDetector.onTouchEvent(event);
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    return true;
                case MotionEvent.ACTION_UP:
                    return true;
                case MotionEvent.ACTION_MOVE:
                    return true;
            }
            return false;
        }
    });
    

提交回复
热议问题