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

我试过这样的方法:

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

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

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


当前回答

如果你计划使用setTextAppearance,你应该知道它会用继承自主题的样式覆盖文本颜色。所以如果你想两者都用,然后再设置颜色。

如此:

textView.setTextAppearance(context, android.R.style.TextAppearance_Medium);
textView.setTextColor(Color.RED);

这将导致你的textcolor为白色(暗主题)或黑色(浅主题):

textView.setTextColor(Color.RED);
textView.setTextAppearance(context, android.R.style.TextAppearance_Medium);

与此相反,在XML中顺序是任意的。

其他回答

您也只能从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));
textView.setTextColor(ContextCompat.getColor(getApplicationC‌​ontext(),R.color.col‌​orWhite)); 

在colors.xml文件中,输入如下代码:

<color name="colorWhite">#FFFFFF</color>
TextView text = new TextView(context);
text.setTextColor(Color.parseColor("any hex value of a color"));

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

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

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

TextView textresult = (TextView)findViewById(R.id.textView1);
textresult.setTextColor(Color.GREEN);