在XML中,我们可以通过textColor属性设置文本颜色,比如android:textColor="#FF0000"。但是我如何通过编码来改变它呢?
我试过这样的方法:
holder.text.setTextColor(R.color.Red);
其中holder只是一个类,文本类型为TextView。红色是字符串中设置的RGB值(#FF0000)。
但是它显示的不是红色而是另一种颜色。我们可以在setTextColor()中传递什么样的参数?在文档中,它说的是int,但它是资源引用值还是其他什么?
如果你仍然想在XML文件中指定颜色:
<color name="errorColor">#f00</color>
然后在代码中使用以下两个方法之一引用它:
textView.setTextColor(getResources().getColor(R.color.errorColor, getResources().newTheme()));
or
textView.setTextColor(getResources().getColor(R.color.errorColor, null));
第一个可能是可取的,如果你编译针对Android M,但你传递的主题可以为空,所以也许这对你更容易?
如果你在使用Compat库,你可以这样做
textView.setTextColor(ContextCompat.getColor(context, R.color.errorColor));
在文本视图中设置颜色有很多不同的方法。
Add color value in studio res->values->colors.xml as
<color name="color_purple">#800080</color>
Now set the color in xml or actvity class as
text.setTextColor(getResources().getColor(R.color.color_purple)
If you want to give color code directly use below Color.parseColor code
textView.setTextColor(Color.parseColor("#ffffff"));
You can also use RGB
text.setTextColor(Color.rgb(200,0,0));
Use can also use direct hexcode for textView. You can also insert plain HEX, like so:
text.setTextColor(0xAARRGGBB);
You can also use argb with alpha values.
text.setTextColor(Color.argb(0,200,0,0));
a for Alpha (Transparent) v.
And if you're using the Compat library you can do something like this
text.setTextColor(ContextCompat.getColor(context, R.color.color_purple));
如果你计划使用setTextAppearance,你应该知道它会用继承自主题的样式覆盖文本颜色。所以如果你想两者都用,然后再设置颜色。
如此:
textView.setTextAppearance(context, android.R.style.TextAppearance_Medium);
textView.setTextColor(Color.RED);
这将导致你的textcolor为白色(暗主题)或黑色(浅主题):
textView.setTextColor(Color.RED);
textView.setTextAppearance(context, android.R.style.TextAppearance_Medium);
与此相反,在XML中顺序是任意的。