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?
In order to set color of a TextView,
TextView.setTextColor(R.color.YOURCOLOR)
is not enough!It has to be used like this –
OR
I did this way: Create a XML file, called Colors in res/values folder.
My Colors.xml:
To get this colors from the xml file, I've used this code: valor it's a TextView, and ctx it's a Context object. I'm not using it from an Activity, but a BaseAdapter to a ListView. That's why I've used this Context Object.
Hope it helps.
You can use
You can also specify what color you want with Transparency.
a for Alpha (Transparent) value r-red g-green b-blue
If you are in an adapter and still want to use a color defined in resources you can try the following approach:
There are many different ways to set color on text view.
Add color value in studio res->values->colors.xml as
Now set the color in xml or actvity class as
If you want to give color code directly use below Color.parseColor code
You can also use RGB
Use can also use direct hexcode for textView. You can also insert plain HEX, like so:
You can also use argb with alpha values.
a for Alpha (Transparent) v.
And if you're using the Compat library you can do something like this
From API 23 onward,
getResources().getColor()
is deprecated.Use this instead: