Search code examples
androidbuttongestures

Android: Detect if user touches and drags out of button region?


In Android, how can we detect if a user touches on button and drags out of region of this button?


Solution

  • Check the MotionEvent.MOVE_OUTSIDE: Check the MotionEvent.MOVE:

    private Rect rect;    // Variable rect to hold the bounds of the view
    
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            // Construct a rect of the view's bounds
            rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
    
        }
        if(event.getAction() == MotionEvent.ACTION_MOVE){
            if(!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())){
                // User moved outside bounds
            }
        }
        return false;
    }
    

    NOTE: If you want to target Android 4.0, a whole world of new possibilities opens: http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_HOVER_ENTER