How to tell if an X and Y coordinate are inside my button?

Consider using FrameLayout (or any other subclass of ViewGroup) instead of ViewGroup directly. Because your current implementation of onLayout method is not correct, which will lead you to problems with displaying of child views.

Now, closer to your question. You should ininitialize Rect and just store left, top, right and bottom position of your Bitmap. As I can see, currently you're initialized r variable, but not using it anywhere.

So, you can initialize it like this:

r = new Rect(100, 100, 100 + bit.getWidth(), 100 + bit.getHeight());

Now in onTouchEvent you can just check:

r.contains((int) event.getX(), (int) event.getY());

this works for any view

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (inViewInBounds(myButtonView, (int) event.getRawX(), (int) event.getRawY())) {
                    // User moved outside bounds
                    Log.e("dispatchTouchEvent", "you touched inside button");
                } else {
                    Log.e("dispatchTouchEvent", "you touched outside button");
                }

        }
        return super.dispatchTouchEvent(event);
    }

 Rect outRect = new Rect();
    int[] location = new int[2];


 private boolean inViewInBounds(View view, int x, int y) {
        view.getDrawingRect(outRect);
        view.getLocationOnScreen(location);
        outRect.offset(location[0], location[1]);
        return outRect.contains(x, y);
    }

Rect rect = new Rect(); 
getHitRect(rect);
if (rect.contains((int) event.getX(), (int) event.getY())) {}

you can use getHitRect(Rect). it returns the Hit rectangle in parent's coordinates. Here the documentation

Tags:

Java

Android