Can't handle both click and touch events simultaneously

后端 未结 12 2045
时光说笑
时光说笑 2020-12-01 03:45

I am trying to handle touch events and click events on a button. I do the following:

button.setOnClickListener(clickListener);
button.setOnTouchListener(touc         


        
12条回答
  •  借酒劲吻你
    2020-12-01 04:08

    thanks to @Nicolas Duponchel this is how i achieved both onClick and onTouch events

    private short touchMoveFactor = 10;
        private short touchTimeFactor = 200;
        private PointF actionDownPoint = new PointF(0f, 0f);
        private long touchDownTime = 0L;
    
     @Override
        public boolean onTouchEvent(MotionEvent event) {
            final int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN: {
                Log.d(TAG, "onTouch: _____________ACTION_DOWN");
                        actionDownPoint.x = event.getX();
                        actionDownPoint.y = event.getY();
                        touchDownTime = System.currentTimeMillis();
                        break;
                    }
                    case MotionEvent.ACTION_UP: {
                        Log.d(TAG, "onTouch: _____________ACTION_UP");
               //check if the user's finger is still close to the point he/she clicked 
                            boolean isTouchLength = (Math.abs(event.getX() - actionDownPoint.x)
                                    + Math.abs(event.getY() - actionDownPoint.y)) < touchMoveFactor;
            //check if it's not been more than @touchTimeFactor=200 ms
                            boolean isClickTime = System.currentTimeMillis() - touchDownTime < touchTimeFactor;
                                 if (isTouchLength && isClickTime) performClick();
        //ACTION_UP logic goes below this line
         .....
         .....
    
                        break;
                    }
    
                    case MotionEvent.ACTION_MOVE: {
    //move method should not work if the click was too short i.e click time +100 ms
                    if (System.currentTimeMillis() - touchDownTime < touchTimeFactor+100) return true;
                    Log.d(TAG, "onTouch: _____________ACTION_MOVE");
    
    // move method logic goes below this line
      .....
      .....
        }}}
    

提交回复
热议问题