user1282637
user1282637

Reputation: 1867

Detecting a press and then a movement outside of the view

I have a listener on a 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;
        }
    });

This changes the color when I press down/up on the Layout. What I want to detect is when the user presses the screen, but moves there finger off of the view (but still pressed). I'm not sure how to go about doing this. Thanks.

Upvotes: 0

Views: 80

Answers (1)

Adam W
Adam W

Reputation: 1012

Here you go. Should make background black on down, and up on white. If finger is moved out of view it returns to white.

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());
    }

Upvotes: 2

Related Questions