在XML中,我们可以通过textColor属性设置文本颜色,比如android:textColor="#FF0000"。但是我如何通过编码来改变它呢?

我试过这样的方法:

holder.text.setTextColor(R.color.Red);

其中holder只是一个类,文本类型为TextView。红色是字符串中设置的RGB值(#FF0000)。

但是它显示的不是红色而是另一种颜色。我们可以在setTextColor()中传递什么样的参数?在文档中,它说的是int,但它是资源引用值还是其他什么?


当前回答

你应该使用:

holder.text.setTextColor(Color.RED);

当然,您可以使用Color类中的各种函数来获得相同的效果。

Color.parseColor (Manual) (like LEX uses) text.setTextColor(Color.parseColor("#FFFFFF")); Color.rgb and Color.argb (Manual rgb) (Manual argb) (like Ganapathy uses) holder.text.setTextColor(Color.rgb(200,0,0)); holder.text.setTextColor(Color.argb(0,200,0,0)); And of course, if you want to define your color in an XML file, you can do this: <color name="errorColor">#f00</color> because the getColor() function is deprecated1, you need to use it like so: ContextCompat.getColor(context, R.color.your_color); You can also insert plain HEX, like so: myTextView.setTextColor(0xAARRGGBB); Where you have an alpha-channel first, then the color value.

当然,可以查看完整的手册,公共类Color extends Object。


这段代码以前也在这里:

textView.setTextColor(getResources().getColor(R.color.errorColor));

这个方法现在在Android m中被弃用了。但是你可以在支持库中的contextCompat中使用它,就像现在的例子所显示的那样。

其他回答

你可以使用

holder.text.setTextColor(Color.rgb(200,0,0));

你也可以用透明度指定你想要的颜色。

holder.text.setTextColor(Color.argb(0,200,0,0));

a代表Alpha(透明)值r-红g-绿b-蓝

在文本视图中设置颜色有很多不同的方法。

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));

我相信,如果你想指定一个颜色作为资源(在XML文件中),你必须提供它的ARGB值(不仅仅是RGB值)。

尝试将颜色值更改为#FFFF0000。它应该给你红色。

Kotlin扩展解决方案

添加这些可以使更改文本颜色更简单

用于设置ColorInt

myView.textColor = Color.BLACK // or Color.parseColor("#000000"), etc.

var TextView.textColor: Int
get() = currentTextColor
set(@ColorInt color) {
    setTextColor(color)
}

用于设置颜色分辨率

myView.setTextColorRes(R.color.my_color)

fun TextView.setTextColorRes(@ColorRes colorRes: Int) {
    val color = ContextCompat.getColor(context, colorRes)
    setTextColor(color)
}
TextView color= (TextView)findViewById(R.id.color);
text.setTextColor(Color.RED);