How to change button background when button state

2019-08-17 13:39发布

问题:

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 it even if I release finger from it. And then if i press it the second time it must change background image again. I know that I must check what background is there at the moment but can't understand how to do it.

I've tried use getBackground method but it wasn't helpful for me. I even tried to create an XML file with selector which contains three state of my button, but it worked only until the moment I release finger from button.

回答1:

You could have a global variable storing the background int:

private int backgroundNumber = 0;

Then, in onClick() you could do something like this:

backgroundNumber++;
switch (backgroundNumber % numberOfBackgrounds) { // numberOfBackgrounds is a constant of how many backgrounds there are
    case 1: 
        button.setBackgroundResource(R.drawable.background1);
        break;
    // Do cases for all the backgrounds
}

I think that should work.



回答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)
    void onButtonActionClicked() {
        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;
        }
    }