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

我试过这样的方法:

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

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

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


当前回答

用于提供rgb值:text.setTextColor(Color.rgb(200,0,0)); 从十六进制值解析颜色: text.setTextColor (Color.parseColor (" # FFFFFF "));

其他回答

在layout.xml中使用以下代码

<TextView  android:id="@+id/textView1"    
android:layout_width="wrap_content"    
android:layout_height="wrap_content" 
android:text="@string/add"
android:layout_marginTop="16dp"
android:textAppearance="?
android:attr/textAppearanceMedium"
android:textColor="#25383C"
android:textSize="13sp" />

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        android:layout_marginTop="16dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#25383C"
        android:textSize="13sp" />

如果你仍然想在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));

我这样做的一个TextView在一个ViewHolder为一个RecyclerView。我不太确定为什么,但它在ViewHolder初始化时对我不起作用。

public ViewHolder(View itemView) {
    super(itemView);
    textView = (TextView) itemView.findViewById(R.id.text_view);
    textView.setTextColor(context.getResources().getColor(R.color.myColor));
    // Other stuff
}

但是当我把它移到onBindViewHolder时,它工作得很好。

public void onBindViewHolder(ViewHolder holder, int position){
    // Other stuff
    holder.textView.setTextColor(context.getResources().getColor(R.color.myColor));
}

希望这能帮助到一些人。

TextView text = new TextView(context);
text.setTextColor(Color.parseColor("any hex value of a color"));

以上代码在我这边工作。这里text是一个需要设置颜色的TextView。

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