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

我试过这样的方法:

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

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

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


当前回答

如果你在适配器中,仍然想使用在资源中定义的颜色,你可以尝试以下方法:

holder.text.setTextColor(holder.text.getContext().getResources().getColor(R.color.myRed));

其他回答

如果你在适配器中,仍然想使用在资源中定义的颜色,你可以尝试以下方法:

holder.text.setTextColor(holder.text.getContext().getResources().getColor(R.color.myRed));

使用适配器,您可以使用以下代码设置文本颜色:

holder.text_view = (TextView) convertView.findViewById(R.id.text_view);
holder.text_view.setTextColor(Color.parseColor("#FF00FF"));

类似地,我使用color.xml:

<color name="white">#ffffff</color>
    <color name="black">#000000</color>   

设置TextView背景如下:

textView.setTextColor(R.color.white);

我得到了一个不同的颜色,但当我使用下面的代码,我得到了实际的颜色。

textView.setTextColor(Color.parseColor("#ff6363"));

我这样做的一个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));
}

希望这能帮助到一些人。

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