1

I am creating my first Android app using this guide as a reference. Currently, I have a red button on my canvas and when the user clicks the button a boolean (green) will be set to true in order for the button's bitmap to a green button.

That part of the application works, however it works regardless where the user clicks on the canvas. I only want the boolean to be changed when the user clicks on the button's bitmap. Here is what I currently have in my code:

The onTouchEvent() method

    @Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {

        button.handleActionDown((int)event.getX(), (int)event.getY());

        if (button.isTouched()) {
            green = true;
        }
    } if (event.getAction() == MotionEvent.ACTION_MOVE) {

    } if (event.getAction() == MotionEvent.ACTION_UP) {
        if (button.isTouched()) {
            green = false;
            button.setTouched(false);
        }
    }
    return true;
}

The handleActionDown() Method

    public void handleActionDown(int eventX, int eventY) {
    if (eventX >= (x - bitmap.getWidth() / 2) && (eventX <= (x + bitmap.getWidth()/2))) {
        if (eventY >= (y - bitmap.getHeight() / 2) && (eventY <= (y + bitmap.getHeight()/2))) {
            setTouched(true);

        } else {
            setTouched(false);
        }
    } else {
        setTouched(false);
    }
}

Can anybody see what I am missing in order for the ACTION_DOWN event to make it so it only triggers when the bitmap's bitmap is touched?

Regards

4

1 回答 1

0

避免将 onTouchEvent 与按钮一起使用,最好使用 onClick,因为操作系统会检测是否单击了特定按钮,而不必计算按钮的位置

一、设置onClickListener

btn.setOnClickListener(this);

这假设当前类 implements View.OnClickListener,所以如果你不实现它,你要么必须使用不同的类,要么创建一个匿名内部类。

然后,在该onClick方法中,确保 ID 匹配并在 if 语句(或 switch 语句)中添加您想要执行的任何操作

@Override
public void onClick(View v) {

    if(v.getId() == R.id.btn1){
        //do whatever you want on press
    }
}
于 2016-07-04T10:40:23.843 回答