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

我试过这样的方法:

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

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

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


当前回答

使用适配器,您可以使用以下代码设置文本颜色:

holder.text_view = (TextView) convertView.findViewById(R.id.text_view);
holder.text_view.setTextColor(Color.parseColor("#FF00FF"));

其他回答

如果你计划使用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中顺序是任意的。

在layout.xml中使用以下代码

<TextView  android:id="@+id/textView1"    
android:layout_width="wrap_content"    
android:layout_height="wrap_content" 
android:text="@string/add"
android:layout_marginTop="16dp"
android:textAppearance="?
android:attr/textAppearanceMedium"
android:textColor="#25383C"
android:textSize="13sp" />

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        android:layout_marginTop="16dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#25383C"
        android:textSize="13sp" />
holder.userType.setTextColor(context.getResources().getColor(
                    R.color.green));

从API 23开始,getResources(). getcolor()已弃用。

用这个代替:

textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.color_black));
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))
}