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

后端 未结 10 2159
暖寄归人
暖寄归人 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:16

    Here's another solution that is very simple and doesn't require you to worry about the finger being moved. If you are basing a click as simply the distance moved then how can you differentiate a click and a long click.

    You could put more smarts into this and include the distance moved, but i'm yet to come across an instance when the distance a user can move in 200 milliseconds should constitute a move as opposed to a click.

    setOnTouchListener(new OnTouchListener() {
        private static final int MAX_CLICK_DURATION = 200;
        private long startClickTime;
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    startClickTime = Calendar.getInstance().getTimeInMillis();
                    break;
                }
                case MotionEvent.ACTION_UP: {
                    long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                    if(clickDuration < MAX_CLICK_DURATION) {
                        //click event has occurred
                    }
                }
            }
            return true;
        }
    });
    

提交回复
热议问题