Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

view.getHitRect(rect) not working

Tags:

android

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.
 }
like image 496
Android Developer Avatar asked Dec 18 '12 06:12

Android Developer


1 Answers

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());
}
like image 140
Adam W Avatar answered Nov 15 '22 06:11

Adam W