Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 613
anticafe Avatar asked Jun 20 '11 11:06

anticafe


2 Answers

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

like image 56
Entreco Avatar answered Oct 13 '22 18:10

Entreco


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.

like image 28
0xMatthewGroves Avatar answered Oct 13 '22 16:10

0xMatthewGroves