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.
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.RemotableViewM开发者_开发知识库ethod
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 accepts 0xAARRGGBB
. Whenever you put "0xFF0000"
, you are actually giving the value "0x00FF0000"
which gives it an alpha value of "0" which is why the TextView
is 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.
Try this
take instance of TextView
and call setTextColor
method
suppose you have TextView with id myTextView, then first get the instance of it
TextView myText = (TextView) findViewById(R.id.myTextView);
then call setTextColor
method
myText .setTextColor(android.graphics.Color.RED);
OR
myText .setTextColor(android.graphics.Color.rgb(int red,int green,int blue);
Try the following
textView.setTextColor(Color.rgb(0,0,0));
精彩评论