在XML中,我们可以通过textColor属性设置文本颜色,比如android:textColor="#FF0000"。但是我如何通过编码来改变它呢?
我试过这样的方法:
holder.text.setTextColor(R.color.Red);
其中holder只是一个类,文本类型为TextView。红色是字符串中设置的RGB值(#FF0000)。
但是它显示的不是红色而是另一种颜色。我们可以在setTextColor()中传递什么样的参数?在文档中,它说的是int,但它是资源引用值还是其他什么?
您也只能从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在一个ViewHolder为一个RecyclerView。我不太确定为什么,但它在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));
}
希望这能帮助到一些人。