3

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?

LiorZ
  • 331
  • 1
  • 5
  • 15

2 Answers2

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