Android MotionEvent: find out if motion happened outside the view

Yury Pogrebnyak picture Yury Pogrebnyak · Jun 23, 2012 · Viewed 10k times · Source

I have a button and OnTouchListener attached to it. How can I find if motion (when user presses the button) happened inside or outside it? Both event.getAction() and event.getActionMasked() return only 0, 1 or 2, which is ActionDown, ActionUp, ActionMove, respectively. There's a constant MotionEvent.ACTION_OUTSIDE, which is 4, but somehow I don't receive it even if I drag touch outside the button - I still receive 2 from both methods. What's the problem?

UPD: I' ve found nice solution - just check focused state on view after ACTION_UP. If it's not focused, it means that movement happened outside the view.

Answer

Derzu picture Derzu · Sep 10, 2016

The MotionEvent.ACTION_OUTSIDE does not works for View's.

One solution is get the X and Y touch position and verify if it is inside the bounds of the View. It can be done like that:

@Override
public boolean onTouchEvent(MotionEvent e) {
    if (isInside())
        Log.i(TAG, "TOUCH INSIDE");
    else
        Log.i(TAG, "TOUCH OUTSIDE");
    return true;
}

private boolean isInside(View v, MotionEvent e) {
    return !(e.getX() < 0 || e.getY() < 0
            || e.getX() > v.getMeasuredWidth()
            || e.getY() > v.getMeasuredHeight());
}