以编程方式更改可绘制onClick的按钮背景

问题描述:

我试图切换按钮的背景可绘制对象,以便当用户单击按钮时其背景被更改,并且当用户再次单击按钮时其背景恢复为默认.这是我的代码:

I am trying to toggle my button's background drawables, so that when the user clicks the button its background is changed and when the user clicks the button again its background returns to defaul. Here is my code:

public void Favorites(View V) {
  Button star = (Button) findViewById(R.id.buttonStar);
  if(star.getBackground().equals(R.drawable.btn_star_off)) {
    star.setBackgroundResource(R.drawable.btn_star_on);
  } else {               
    star.setBackgroundResource(R.drawable.btn_star_off);
  }
}

我很确定这不是您将if语句一起使用的方式.有人可以建议一种方法吗?

I am pretty sure this is not how you use drawables with if statements. Can someone suggest a way to do it?

private boolean isButtonClicked = false; // You should add a boolean flag to record the button on/off state

protected void onCreate(Bundle savedInstanceState) {
    ......
    Button star = (Button) findViewById(R.id.buttonStar);
    star.setOnClickListener(new OnClickListener() { // Then you should add add click listener for your button.
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.buttonStar) {
                isButtonClicked = !isButtonClicked; // toggle the boolean flag
                v.setBackgroundResource(isButtonClicked ? R.drawable.btn_star_on : R.drawable.btn_star_off);
            }
        }
    });
}