In Android, how can we detect if a user touches on button and drags out of region of this button?
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
The answer posted by Entreco needed some slight tweaking in my case. I had to substitute:
if(!rect.contains((int)event.getX(), (int)event.getY()))
for
if(!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY()))
because event.getX()
and event.getY()
only apply to the ImageView itself, not the entire screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With