How to use setTextColor for Android Radio Buttons?
Asked Answered
O

2

5

I am trying to change the text color of a RadioButton (which is defined in an xml layout and is in a RadioGroup) on selecting it.

When I change the text color directly in the Eclipse Android Layout Editor by setting the TextColor property to "@color/red" (which I defined in strings.xml), it works just fine, but when I try to do this programmatically during runtime as

myRadioButton.setTextColor(R.color.red); 

it only turns the color to grey, not to red as intended.

R.color.red (@color/red) is correctly defined as a hex value ("#FF0000"), but it does turn the text color to red in the layout editor, but not via a Java command.

Ox answered 29/3, 2012 at 6:30 Comment(4)
use getResources().getColor(R.color.red) instead of R.color.redSennight
Thank you for the answer..but when using this and unselecting the button the color does not go back to the default color. How can I achieve this?Ox
try to change in onCheckedChanged() to default color?Sennight
Had to customize a bit but it works now..thank you so much!Ox
A
17

if your color.xml is like:

<color name="errorColor">#f00</color>

and then use this code to show it:

myRadioButton.setTextColor(getResources().getColor(R.color.red));
Aidoneus answered 29/3, 2012 at 6:41 Comment(1)
Just a heads up, getColor() has been deprecated in API 23, and now we have ContextCompat.getColor(context, R.color.your_color);Whitewood
E
4

there are some other ways to do so

myRadioButton.setTextColor(Color.RED);
or
myRadioButton.setTextColor(Color.rgb(red, green, blue)); 
// where red green and blue are the int values

edited if you want to get from resources then use getResources().getColor(R.color.red) ;

Eusebiaeusebio answered 29/3, 2012 at 6:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.