允许矩形可点击 - android

Lio*_*orZ 3 android

我用画布写了一个视图,其中包含许多矩形.我希望这些矩形用作打开新活动的按钮.我该怎么做?

Epi*_*aos 9

你需要小心Suri Sahani的例子,在任何限定为触摸事件的动作上调用onTouchEvent,这意味着按下,释放,移动手势等(Android事件监听器文档).要正确使用onTouchEvent,您需要检查MotionEvent类型.

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;
}
Run Code Online (Sandbox Code Playgroud)