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?
You should use:
For a sanity check, I just tried it, because I had a project open anyway, and yes, it's nice and red ;D
You can use various functions from the
Color
class to get the same effect of course.Color.parseColor
(Manual) (like LEX uses)Color.rgb
andColor.argb
(Manual rgb) (Manual argb) (like Ganapathy uses)And of course, if you want to define your color in an
XML
file, you can do this:because the
getColor()
function is deprecated1, you need to use it like so:You can also insert plain HEX, like so:
Where you have an alpha-channel first, then the color value.
Check out the complete manual of course, public class Color extends Object.
1This code used to be in here as well:
This method is now deprecated in Android M. You can however use it from the contextCompat in the support library, as the example now shows.
Above code is working on my side. Here
text
is a TextView on which color is needed to be set.Similarly, I was using
color.xml
:For setting the
TextView
background like:I was getting a different color, but when I used the below code I got the actual color.
text.setTextColor(getResource().getColor(R.color.black))
you have create black color in color.xml.OR
text.setTextColor(Color.parseColor("#000000"))
here type desired hexcodeOR
text.setTextColor(Color.BLACK)
you can use static color fieldsFor providing rgb values:
text.setTextColor(Color.rgb(200,0,0));
For parsing the color from a hex value:
text.setTextColor(Color.parseColor("#FFFFFF"));