LongClick event happens too quickly. How can I increase the clicktime required to trigger it?

后端 未结 8 1514
暖寄归人
暖寄归人 2020-12-08 21:26

In an application I\'m working on, I have the requirement that a user must click & hold a component for a period time before a certain action occurs.

I\'m curren

8条回答
  •  眼角桃花
    2020-12-08 22:18

    For future reference, here is my implementation :)

    public abstract class MyLongClickListener implements View.OnTouchListener {
    
        private int delay;
        private boolean down;
        private Runnable callback;
        private RectF mRect = new RectF();
    
        public MyLongClickListener(int delay) {
            this.delay = delay;
            this.callback = new Runnable() {
                @Override
                public void run() {
                    down = false;
                    onLongClick();
                }
            };
        }
    
        public abstract void onLongClick();
    
        @Override
        public boolean onTouch(View v, MotionEvent e) {
            if (e.getPointerCount() > 1) return true;
    
            int action = e.getAction();
            if (action == MotionEvent.ACTION_DOWN) {
                down = true;
                mRect.set(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
                v.postDelayed(callback, delay);
                return false;
    
            } else if (action == MotionEvent.ACTION_MOVE) {
                if (down && !mRect.contains(v.getLeft() + e.getX(), v.getTop() + e.getY())) {
                    v.removeCallbacks(callback);
                    down = false;
                    return false;
                }
    
            } else if (action == MotionEvent.ACTION_UP) {
                if (down) {
                    v.removeCallbacks(callback);
                    v.performClick();
                }
                return true;
    
            } else if (action == MotionEvent.ACTION_CANCEL) {
                v.removeCallbacks(callback);
                down = false;
            }
    
            return false;
        }
    
    }
    

    Usage:

    textView.setOnTouchListener(new MyLongClickListener(2000) {
        @Override
        public void onLongClick() {
            System.err.println("onLongClick");
        }
    });
    

提交回复
热议问题