How To Change Button Background When Button State Is Changed
Wondering how can I change my button background programmatically by setting onClickListener. I mean that when I firstly pressed my button it changes its background image and save
Solution 1:
You could have a global variable storing the background int:
privateint backgroundNumber = 0;
Then, in onClick() you could do something like this:
backgroundNumber++;
switch (backgroundNumber % numberOfBackgrounds) { // numberOfBackgrounds is a constant of how many backgrounds there arecase1:
button.setBackgroundResource(R.drawable.background1);
break;
// Do cases for all the backgrounds
}
I think that should work.
Solution 2:
Try like this.
You know how many states you have. Use an int variable (lest say buttonState) to save button state (ex. states 1,2,3. MAX_STATE = 3).
On click just change state and replace background depending on the current buttonState variable value.
@Click(R.id.button_action)voidonButtonActionClicked() {
buttonState = ++buttonState % BTN_STATE_MAX;
switch (buttonState){
case BTN_SAVE:
button.setBackgroundResource(R.drawable.button_save);
break;
case BTN_LOAD:
button.setBackgroundResource(R.drawable.button_load);
break;
case BTN_DELETE:
button.setBackgroundResource(R.drawable.button_delete);
break;
}
}
Post a Comment for "How To Change Button Background When Button State Is Changed"