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?
If you plan to use setTextAppearance you should know that it will overwrite the text color with the style inherited from the theme. So if you want to use both, set the color afterwards.
This works:
While this will cause your textcolor to be for instance white(for dark theme) or black(for the light theme):
Contrary to this in XML the order is arbitrary.
In Adapter you can set the text color by using this code:
if you want to give color code directly then use
or if you want to give color code from colors folder then use
getColor() is depreceted
So try this way:
I was doing this for a TextView in a ViewHolder for a RecyclerView. I'm not so sure why, but it didn't work for me in the ViewHolder initialization.
But when I moved it to the onBindViewHolder, it worked fine.
Hope this helps someone.