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?
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);
}
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With