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

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

    To get most optimized recognition of click event We have to consider 2 things:

    1. Time difference between ACTION_DOWN and ACTION_UP.
    2. Difference between x's,y's when user touch and when release the finger.

    Actually i combine the logic given by Stimsoni and Neethirajan

    So here is my solution:

            view.setOnTouchListener(new OnTouchListener() {
    
            private final int MAX_CLICK_DURATION = 400;
            private final int MAX_CLICK_DISTANCE = 5;
            private long startClickTime;
            private float x1;
            private float y1;
            private float x2;
            private float y2;
            private float dx;
            private float dy;
    
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                // TODO Auto-generated method stub
    
                        switch (event.getAction()) 
                        {
                            case MotionEvent.ACTION_DOWN: 
                            {
                                startClickTime = Calendar.getInstance().getTimeInMillis();
                                x1 = event.getX();
                                y1 = event.getY();
                                break;
                            }
                            case MotionEvent.ACTION_UP: 
                            {
                                long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                                x2 = event.getX();
                                y2 = event.getY();
                                dx = x2-x1;
                                dy = y2-y1;
    
                                if(clickDuration < MAX_CLICK_DURATION && dx < MAX_CLICK_DISTANCE && dy < MAX_CLICK_DISTANCE) 
                                    Log.v("","On Item Clicked:: ");
    
                            }
                        }
    
                return  false;
            }
        });
    

提交回复
热议问题