检测按下,然后检测视图外的移动

Detecting a press and then a movement outside of the view

我在 RelativeLayout 上有一个监听器:

 rl.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                rl.setBackgroundColor(Color.BLACK);
            }

            if ((event.getAction() == MotionEvent.ACTION_UP)) {
                rl.setBackgroundColor(Color.WHITE);
                v.performClick();
            }
            return false;
        }
    });

当我在布局上按 down/up 时,这会更改颜色。我想要检测的是用户按下屏幕,但将手指移出视图(但仍按下)。我不知道该怎么做。谢谢

给你。应该使背景黑色向下,白色向上。如果手指移出视野,它 returns 变为白色。

rl.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {  
        if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
            if (isTouchInView(view, motionEvent)) {
                //lifted finger while touch was in view
                view.performClick();
            }

            view.setBackgroundColor(Color.WHITE);
            return true;
        }

        if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
            //finger still down and left view
            if (!isTouchInView(view, motionEvent)) {
                view.setBackgroundColor(Color.WHITE);
            }
        }

        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            //pressed down on view
            view.setBackgroundColor(Color.BLACK);
            return true;
        }

        if (motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
            //a cancel event was received, finger up out of view
            view.setBackgroundColor(Color.WHITE);
            return true;
        }
        return false;
    }

    private boolean isTouchInView(View view, MotionEvent event) {
        Rect hitBox = new Rect();
        view.getGlobalVisibleRect(hitBox);
        return hitBox.contains((int) event.getRawX(), (int) event.getRawY());
    }