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:25
textView.setTextColor(ContextCompat.getColor(getApplicationC‌​ontext(),R.color.col‌​orWhite)); 

In the colors.xml file, write in the code below:

<color name="colorWhite">#FFFFFF</color>
查看更多
谁念西风独自凉
3楼-- · 2018-12-31 10:26

And another one:

TextView text = (TextView) findViewById(R.id.text);
text.setTextColor(Color.parseColor("#FFFFFF"));
查看更多
高级女魔头
4楼-- · 2018-12-31 10:27
text1.setTextColor(Color.parseColor("#000000"));
查看更多
笑指拈花
5楼-- · 2018-12-31 10:30

I normally do this for any views:

myTextView.setTextColor(0xAARRGGBB);

where

  • AA defines alpha (00 for transparent, FF for opaque)

  • RRGGBB defines the normal HTML color code (like FF0000 for red).

查看更多
梦寄多情
6楼-- · 2018-12-31 10:31

You can do this only from an XML file too.

Create a color.xml file in the values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="textbody">#ffcc33</color>

</resources>

Then in any XML file, you can set color for text using,

android:textColor="@color/textbody"

Or you can use this color in a Java file:

final TextView tvchange12 = (TextView) findViewById(R.id.textView2);
//Set color for textbody from color.xml file
tvchange1.setTextColor(getResources().getColor(R.color.textbody));
查看更多
宁负流年不负卿
7楼-- · 2018-12-31 10:32

I believe that if you want to specify a color as a resource (in the XML file), you'll have to provide its ARGB value (not simply the RGB value).

Try changing your color value to #FFFF0000. It should give you RED.

查看更多
登录 后发表回答