LiorZ
LiorZ

Reputation: 341

Allowing rectangle to be clickable - android

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?

Upvotes: 3

Views: 9078

Answers (2)

EpicOfChaos
EpicOfChaos

Reputation: 842

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;
}

Upvotes: 11

DRiFTy
DRiFTy

Reputation: 11369

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.

Upvotes: 1

Related Questions