The top 2 answers are good, except when the view is inside the scroll: when the scroll occurs because you move your finger, it is still registered as a touch event, but not as a MotionEvent.ACTION_MOVE event. Therefore, to improve the answer (which is only needed if your view is inside the scroll element):
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 bounds rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); } else if(rect != null && !rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())){ // User moved outside bounds } return false; }
I tested this on Android 4.3 and Android 4.4
I did not notice any differences between Moritz's answer and top 2, but this also applies to his answer:
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 bounds rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); } else if (rect != null){ v.getHitRect(rect); if(rect.contains( Math.round(v.getX() + event.getX()), Math.round(v.getY() + event.getY()))) { // inside } else { // outside } } return false; }
Bart Burg Apr 14 '15 at 8:05 2015-04-14 08:05
source share