Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing rectangle to be clickable - android

Tags:

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?

like image 773
LiorZ Avatar asked Nov 25 '25 09:11

LiorZ


1 Answers

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;
}
like image 143
EpicOfChaos Avatar answered Nov 26 '25 23:11

EpicOfChaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!