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

我试过这样的方法:

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

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

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


当前回答

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

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

其他回答

你应该使用:

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中使用它,就像现在的例子所显示的那样。

getColor()被禁用

所以试试这个方法:

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

我是这样做的: 创建一个名为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));

希望能有所帮助。

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

您也只能从XML文件执行此操作。

在values文件夹中创建一个color.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="textbody">#ffcc33</color>

</resources>

然后在任何XML文件中,你可以使用,

android:textColor="@color/textbody"

或者你可以在Java文件中使用这种颜色:

final TextView tvchange12 = (TextView) findViewById(R.id.textView2);
//Set color for textbody from color.xml file
tvchange1.setTextColor(getResources().getColor(R.color.textbody));