Search code examples
androidcsscolorsbackgrounddrawable

Android how to change the button color by the text


I simply wish to change the background color of the button by the value of the text. For example, when I change the text to:

button.setText("YES");

I want to set the background color of the button to green. and when I change the text to:

button.setText("NO");

I want to set the background color of the button to red.

When I change it in the java code like this:

boolean textValueYES = true;
button.setBackgroundColor(textValueYES ? Color.GREEN : Color.RED);

The button loses its drawable.xml settings. Is there a way to add this checking to the drawable xml? Or to set the background color by its text value without losing the drawable settings?


Solution

  • you can create two drawable xml for red and green background color and set that xml programmatically.

    button.setBackgroundResource(textValueYES ? R.drawable.green : R.drawable.red);