Domanda

I'm building an accessibility app for people with bad eyesight where users can choose their own combination of colors. For this reason I need to change buttons' backgrounds programatically depending on their preferences.

I want to set the background color for when the button is not pressed and a different color for when it's pressed. However I doing setBackgroundColor overrides both values.

        ((Button) view).setBackgroundColor(customColor1);

How can I set customColor1 for when the button is not pressed and customColor2 for when it is?

È stato utile?

Soluzione

Try something like this

Button btn = (Button) findViewById(R.id.button);

StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(getResources().getColor(R.color.red)));
stateListDrawable.addState(new int[] {-android.R.attr.state_pressed}, new ColorDrawable(getResources().getColor(R.color.green)));

btn.setBackgroundDrawable(stateListDrawable);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top