How to set the text color of TextView in code?

2018-12-31 10:12发布

In XML, we can set a text color by the textColor attribute, like android:textColor="#FF0000". But how do I change it by coding?

I tried something like:

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

Where holder is just a class and text is of type TextView. Red is an RGB value (#FF0000) set in strings.

But it shows a different color rather than red. What kind of parameter can we pass in setTextColor()? In documentation, it says int, but is it a resource reference value or anything else?

30条回答
无与为乐者.
2楼-- · 2018-12-31 10:36

Using Adapter you can set the text color by using this code:

holder.text_view = (TextView) convertView.findViewById(R.id.text_view);
holder.text_view.setTextColor(Color.parseColor("#FF00FF"));
查看更多
梦寄多情
3楼-- · 2018-12-31 10:36
TextView textresult = (TextView)findViewById(R.id.textView1);
textresult.setTextColor(Color.GREEN);
查看更多
笑指拈花
4楼-- · 2018-12-31 10:37

If you still want to specify your colors in your XML file:

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

Then reference it in your code with one of these two methods:

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

or

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

The first is probably preferable if you're compiling against Android M, however the theme you pass in can be null, so maybe that's easier for you?

And if you're using the Compat library you can do something like this

textView.setTextColor(ContextCompat.getColor(context, R.color.errorColor));
查看更多
笑指拈花
5楼-- · 2018-12-31 10:37

Use:

TextView tv = new TextView(this);
tv.setTextColor(Color.rgb(285,0,0));
查看更多
大哥的爱人
6楼-- · 2018-12-31 10:37
holder.text.setTextColor(Color.rgb(200,0,0));

or

myTextView.setTextColor(0xAARRGGBB);
查看更多
君临天下
7楼-- · 2018-12-31 10:39

use the following code in 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" />
查看更多
登录 后发表回答