Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically change button background drawable 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);
  }
}

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

like image 809
Andre Bounames Avatar asked Mar 29 '15 14:03

Andre Bounames


1 Answers

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);
            }
        }
    });
}
like image 84
li2 Avatar answered Sep 20 '22 12:09

li2