Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 864
Uziel Davidi Avatar asked Feb 07 '23 09:02

Uziel Davidi


2 Answers

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);
like image 189
KDeogharkar Avatar answered Feb 13 '23 06:02

KDeogharkar


You have to do like this just write below of setText()

i.e

button.setText("YES");
setBackgroundResource(R.color.green);

and when

button.setText("NO");
setBackgroundResource(R.color.red);
like image 25
Ajay Pandya Avatar answered Feb 13 '23 07:02

Ajay Pandya