Need help making rectangles function like buttons (Android)
So I'm quite a noob using the Android SDK (I find it very confusing compared to straight java). This is my second day using it, teaching myself the whole way.
With that mentioned, I would like to know how to make a Rect act as a button.
Basically the user will tap on a certain Rectangle (that has been drawn on the screen, but how to draw it is a different question; I am completely lost with Canvas) and then I want to check th开发者_高级运维e x/y coords of where they touched and see if was contained inside the rectangle, at which point the app will do something (like change the text in a textview somewhere on the UI).
I've been trying to do this for about an hour with no luck, if anyone could write up a small piece of source code on how to do this I would appreciate it a lot!
So I'm going to assume you're using a SurfaceView to draw on. What you want should be pretty simple.
First, override the touch event in the surface view and store off the coordinates of the last touch:
@Override
public void onTouchEvent(MotionEvent event) {
x = event.getX();
y = event.getY();
}
Then, check if your rect contains that coordinate:
Rect rect = new Rect() // Your rect
if (rect.contains(x, y) {
// Contained in your rect
} else {
// Not contained in your rect
}
I believe that's what your asking? Let me know if you're still confused.
精彩评论