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

我试过这样的方法:

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

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

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


当前回答

我是这样做的: 创建一个名为Colors in res/values文件夹的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对象。我不是从一个活动使用它,而是从一个BaseAdapter到一个ListView。这就是我使用Context对象的原因。

valor.setTextColor(ctx.getResources().getColor(R.color.azul_credito));

希望能有所帮助。

其他回答

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

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

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

类似地,我使用color.xml:

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

设置TextView背景如下:

textView.setTextColor(R.color.white);

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

textView.setTextColor(Color.parseColor("#ff6363"));
TextView textresult = (TextView)findViewById(R.id.textView1);
textresult.setTextColor(Color.GREEN);

我是这样做的: 创建一个名为Colors in res/values文件夹的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对象。我不是从一个活动使用它,而是从一个BaseAdapter到一个ListView。这就是我使用Context对象的原因。

valor.setTextColor(ctx.getResources().getColor(R.color.azul_credito));

希望能有所帮助。