Programmatically change button background drawable onClick

Andre Bounames picture Andre Bounames · Mar 29, 2015 · Viewed 40.8k times · Source

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

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

Answer

li2 picture li2 · Mar 29, 2015
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);
            }
        }
    });
}