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

我试过这样的方法:

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

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

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


当前回答

在文本视图中设置颜色有很多不同的方法。

Add color value in studio res->values->colors.xml as <color name="color_purple">#800080</color> Now set the color in xml or actvity class as text.setTextColor(getResources().getColor(R.color.color_purple) If you want to give color code directly use below Color.parseColor code textView.setTextColor(Color.parseColor("#ffffff")); You can also use RGB text.setTextColor(Color.rgb(200,0,0)); Use can also use direct hexcode for textView. You can also insert plain HEX, like so: text.setTextColor(0xAARRGGBB); You can also use argb with alpha values. text.setTextColor(Color.argb(0,200,0,0)); a for Alpha (Transparent) v. And if you're using the Compat library you can do something like this text.setTextColor(ContextCompat.getColor(context, R.color.color_purple));

其他回答

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

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

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

在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" />

如果你使用Kotlin,有4种方法:(与Holder)

使用Android资源: holder.textView.setTextColor (Color.GREEN) 使用RGB: holder.textView.setTextColor(颜色。Rgb (255, 87, 34))

3)使用十六进制:

holder.textView.setTextColor(Color.parseColor("#C2185B"))

4)使用项目资源:(需要API级别23)

holder.textView.setTextColor(context.resources.getColor(R.color.colorMax,null))

如果你在适配器中,仍然想使用在资源中定义的颜色,你可以尝试以下方法:

holder.text.setTextColor(holder.text.getContext().getResources().getColor(R.color.myRed));

试试这个:

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