如何在代码中设置TextView的文本颜色?

613
在XML中,我们可以通过textColor属性设置文本颜色,例如android:textColor="#FF0000"。但是我该如何通过编码来更改它呢?
我尝试了以下内容:
holder.text.setTextColor(R.color.Red);

holder 是一个类,textTextView 类型。 红色是在字符串中设置的 RGB 值(#FF0000)。

但它显示的颜色与红色不同。 我们可以在 setTextColor() 中传递什么参数? 在文档中,它说是 int,但它是资源引用值还是其他任何东西?


关于在代码中调整用户界面的注意事项,请考虑在设计时查看用户界面的优点,将运行时更改最小化。 - AlikElzin-kilaka
40个回答

1
我是这样做的: 在res/values文件夹中创建一个名为Colors的XML文件。
我的Colors.xml:
    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="vermelho_debito">#cc0000</color>
    <color name="azul_credito">#4c4cff</color>
    <color name="preto_bloqueado">#000000</color>
    <color name="verde_claro_fundo_lista">#CFDBC5</color>
    <color name="branco">#ffffff</color>
    <color name="amarelo_corrige">#cccc00</color>
    <color name="verde_confirma">#66b266</color>
</resources>

为了从xml文件中获取这些颜色,我使用了以下代码:valor是一个TextView,ctx是一个Context对象。我不是从Activity中使用它,而是从BaseAdapter到ListView中使用。这就是为什么我使用了这个Context对象。
valor.setTextColor(ctx.getResources().getColor(R.color.azul_credito));

希望能有所帮助。


1
为了设置TextView的颜色,TextView.setTextColor(R.color.YOURCOLOR)是不够的!必须像这样使用 -
TextView myText = (TextView) findViewById(R.id.YoutTextViewID);

myText.setTextColor(getResources().getColor(R.color.YOURCOLOR);

或者

myText.setTextColor(Color.parseColor("#54D66A"));

1
holder.userType.setTextColor(context.getResources().getColor(
                    R.color.green));

1
在适配器中,您可以使用以下代码设置文本颜色:
holder.my_text_view = (TextView) convertView.findViewById(R.id.my_text_view);
holder.my_text_view.setTextColor(Color.parseColor("#FFFFFF"));

1
   textViewStatus.setTextColor(res.getColor(R.color.green));

1
如果您想直接提供颜色代码,则使用:

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

如果您想从颜色文件夹中提取颜色代码,则使用以下代码:

textView.setTextColor(R.color.white);

这段代码 textView.setTextColor(R.color.white); 无效。您可以使用 text.setTextColor(getResources().getColor(R.color.color_purple)) 来从 color.xml 中获取颜色。 - Hanako

1

试试这个:

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

3
如前所述,但在此需要重申:getColor已自Android M起被弃用,有可能将来会消失。 - John Lord

1

试试这个:

TextView textview = (TextView) findViewById(R.id.textview );
textview .setTextColor(Color.parseColor("#85F85F"));

0

getColor()已被弃用

所以请尝试这种方式:

 tv_title.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.sf_white));

0

我在RecyclerView的ViewHolder中为一个TextView做了这个操作。但我不太确定为什么,在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));
}

希望这能帮助到某个人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接