How to change button background when button state is changed

邮差的信 提交于 2019-12-11 14:18:16

问题


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


来源:https://stackoverflow.com/questions/25013003/how-to-change-button-background-when-button-state-is-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!