5

I am overriding onInterceptTouch(MotionEvent) for the purpose of allowing horizontal scrolling. What I am finding however is that I cannot detect when the user has touched the embedded v. The x,y on the view are like 2000, 2400 while the MotionEvent.getX(),getY() are like 400,500

View v = findViewById(R.id.myView);

Rect r = new Rect();
v.getHitRect(r);
int[] loc = new int[2];
v.gtLocationOnScreen(loc);

int x = loc[0];
int y = loc[1];

// Result x,y are huge numbers 2400, etc
// event.getX() is 30, event.getY() == 500 nothing close to 2400.

if (r.contains((int)event.getX(), (int)event.getY())
{
   return false;  // this is never true even when I click right on View v.
 }
onkar
  • 4,427
  • 10
  • 52
  • 89
Android Developer
  • 523
  • 2
  • 5
  • 17

2 Answers2

19

I know this is an old question and is mostly answered in the linked post, but I just came across this problem so I thought I'd fill in my solution.

private boolean isTouchInView(View view, MotionEvent event) {
    Rect hitBox = new Rect();
    view.getGlobalVisibleRect(hitBox);
    return hitBox.contains((int) event.getRawX(), (int) event.getRawY());
}
Adam W
  • 972
  • 9
  • 18
3

Try using getRawX() and getRawY(). These will give you the absolute positions you need.

See:

How do I know if a MotionEvent is relative or absolute?

You also have to adjust the location of your destination view to account for any displacement by other views like so:

int[] screenLocation = new int[2];
view.getLocationOnScreen(screenLocation);
hitRect.offset(screenLocation[0] - view.getLeft(), screenLocation[1] - view.getTop());

//Then check if source view is contained in target view

x=event.getRawX();
y=event.getRawY();

if (hitRect.contains(x, y)) {

//do your stuff

}
Community
  • 1
  • 1
Anup Cowkur
  • 20,443
  • 6
  • 51
  • 84
  • result (x,y) of view is (2180,2425), MotionEvent.getRawX,Y = (149,1017) again the r.contains fails – Android Developer Dec 18 '12 at 06:56
  • The problem Anup is that it does not work for any View v. It works if the view is off the main parent view but not for nested views. – Android Developer Dec 18 '12 at 09:45
  • If you think you have an answer then please provide a generic public boolean isWithinView(View v, MotionEvent e) {} that works for any view in any level. I will plug that in. – Android Developer Dec 18 '12 at 09:45
  • I don't really want the api level call to depend on an examination of every layer of the layout. I need something generic. I still am looking for a more generic solution. – Android Developer Dec 18 '12 at 09:51