I wrote a View with canvas, which contains many rectangles. I want these rectangles to be used as a button which will open a new activity. How can I do it?
Asked
Active
Viewed 8,860 times
3
-
Are any of these answers helpful? – EpicOfChaos Aug 31 '11 at 20:30
-
Thank you all for helping. I succeed creating clickable rectangles, but if the rectangle is small, it's very difficult to click on it (only after 5-6 click attempts) – LiorZ Sep 02 '11 at 16:00
-
@LiorZ Hai can you provide working code for this? – Taruni Oct 03 '12 at 07:30
2 Answers
11
You need to be careful with Suri Sahani example, onTouchEvent is called on any action qualified as a touch event, meaning press, release, movement gesture, etc(Android Event Listener Documentation). To use the onTouchEvent properly you need to check the MotionEvent type.
List<Rect> retangles;//Assume these have been drawn in your draw method.
@Override
public boolean onTouchEvent(MotionEvent event) {
int touchX = event.getX();
int touchY = event.getY();
switch(event){
case MotionEvent.ACTION_DOWN:
System.out.println("Touching down!");
for(Rect rect : rectangles){
if(rect.contains(touchX,touchY)){
System.out.println("Touched Rectangle, start activity.");
Intent i = new Intent(<your activity info>);
startActivity(i);
}
}
break;
case MotionEvent.ACTION_UP:
System.out.println("Touching up!");
break;
case MotionEvent.ACTION_MOVE:
System.out.println("Sliding your finger around on the screen.");
break;
}
return true;
}

EpicOfChaos
- 822
- 11
- 23
-
When you use `event.getX()` and `event.getY()` **float** values are returned, so you must type-cast `event.getX()` and `event.getY()` to **int** for use with int-type variables. Also, `event` in the `switch` statement should be `event.getAction()`. – Zach H Jun 30 '14 at 07:16
1
In your onTouchEvent()
just capture the x and y values and you can use the contains(int x, int y)
method in the Rect
class. If contains(x, y)
returns true, then the touch was inside the rectangle and then just create the intent and start the new activity.

DRiFTy
- 11,269
- 11
- 61
- 77