This is my first post here.
I’ve to change a TextView's text color at runtime. There’s a method TextView.setTextColor(int), but it doesn’t work with int values that are not in resources.
For example, a color calculated at runtime such as 0xFF0000 (RGB), not present in R.color, doesn’t work. The TextView is not rendered.
I’ve taken a look at android source code for this, and there are two methods, none of them accept rgb int values as argument:
/**
* Sets the text color for all the states (normal, selected,
* focused) to be this color.
*
* @attr ref android.R.styleable#TextView_textColor
*/
@android.view.RemotableViewMethod
public void setTextColor(int color) {
mTextColor = ColorStateList.valueOf(color);
updateTextColors();
}
/**
* Sets the text color.
*
* @attr ref android.R.styleable#TextView_textColor
*/
public void setTextColor(ColorStateList colors) {
if (colors == null) {
throw new NullPointerException();
}
mTextColor = colors;
updateTextColors();
}
So there’s no way of doing this? Maybe extending TextView?
Thanks in advance.
I think the problem might be you’re not setting the color’s alpha value.
TextView.setTextColor()does not accept 0xRRGGBB values. Instead, it accepts0xAARRGGBB. Whenever you put"0xFF0000", you are actually giving the value"0x00FF0000"which gives it an alpha value of “0” which is why theTextViewis not rendered. Thus, instead of 0xFF0000, try to set it to 0xFFFF0000.Alternatively, you can use Android’s Color class. The method “Color.rgb(int, int, int)” implicitly assigns the alpha value of 255, so calling
"Color.rgb(255, 0, 0)"should yield a red color value for the text.