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

我试过这样的方法:

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

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

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


当前回答

textView.setTextColor(ContextCompat.getColor(getApplicationC‌​ontext(),R.color.col‌​orWhite)); 

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

<color name="colorWhite">#FFFFFF</color>

其他回答

如果你仍然想在XML文件中指定颜色:

<color name="errorColor">#f00</color>

然后在代码中使用以下两个方法之一引用它:

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

or

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

第一个可能是可取的,如果你编译针对Android M,但你传递的主题可以为空,所以也许这对你更容易?

如果你在使用Compat库,你可以这样做

textView.setTextColor(ContextCompat.getColor(context, R.color.errorColor));

尝试使用以下代码:

holder.text.setTextColor(Color.parseColor("F00"));

试试这个:

textView.setTextColor(getResources().getColor(R.color.errorColor, null));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { 
    b.numberDay1.setTextColor(ContextCompat.getColor(requireContext(), R.color.secondary_100))
} else {                
    b.numberDay1.setTextColor(resources.getColor(R.color.secondary_100))
}

类似地,我使用color.xml:

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

设置TextView背景如下:

textView.setTextColor(R.color.white);

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

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