Search code examples
javaandroidandroid-custom-viewcontainsrect

Rect contains(x,y) doesn't trigger


I'm trying to simulate a button click in a custom android view. I need to use the Rect.contains() method for that, but no matter where I click on the rect it is never triggered and doesn't return true.

 rect = new Rect(0, 0, 720, 205);

An example of click coordinates is (401,103), this returns false.

if(rect.contains((int)event.getX(),(int)event.getY())){
                    Log.w("CLICKED","");
                }

"CLICKED" is never logged. I've read the docs and it says 'left <= x < right and top <= y < bottom' to return true

in this example 0<=401<720 and 0<=103<205 which is true but doesnt seem to work.

Any help appreciated


Solution

  • getX() and getY() returns the coordinate relative to the view that dispatches the event. If that view's origin is not at 0, 0 then the it may not satisfy the rect.contains((int)event.getX(),(int)event.getY()) condition.

    However, you can use getRawX() and getRawY() which returns the absolute coordinate, relative to the Screen.

    This might be the case-

    pic1.png