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

我试过这样的方法:

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

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

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


当前回答

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

其他回答

getColor()被禁用

所以试试这个方法:

 tv_title.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.sf_white));

为了设置一个TextView的颜色,TextView. settextcolor (R.color.YOURCOLOR)是不够的!

它必须像这样使用-

TextView myText = (TextView) findViewById(R.id.YoutTextViewID);

myText.setTextColor(getResources().getColor(R.color.YOURCOLOR);

OR

myText.setTextColor(Color.parseColor("#54D66A"));
text1.setTextColor(Color.parseColor("#000000"));

text.setTextColor(getResource(). getcolor (R.color.black))在color.xml中创建黑色。

OR

text.setTextColor(Color.parseColor("#000000"))在这里输入所需的十六进制码

OR

你可以使用静态颜色字段

如果你想给颜色代码直接使用

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

或者如果你想给颜色代码从颜色文件夹然后使用

textView.setTextColor(R.color.white);