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 s
holder.userType.setTextColor(context.getResources().getColor(
R.color.green));
If you are in an adapter and still want to use a color defined in resources you can try the following approach:
holder.text.setTextColor(holder.text.getContext().getResources().getColor(R.color.myRed));
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));
There are many different ways to set color on text view.
Add color value in studio res->values->colors.xml as
<color name="color_purple">#800080</color>
Now set the color in xml or actvity class as
text.setTextColor(getResources().getColor(R.color.color_purple)
If you want to give color code directly use below Color.parseColor code
textView.setTextColor(Color.parseColor("#ffffff"));
You can also use RGB
text.setTextColor(Color.rgb(200,0,0));
Use can also use direct hexcode for textView. You can also insert plain HEX, like so:
text.setTextColor(0xAARRGGBB);
You can also use argb with alpha values.
text.setTextColor(Color.argb(0,200,0,0));
a for Alpha (Transparent) v.
And if you're using the Compat library you can do something like this
text.setTextColor(ContextCompat.getColor(context, R.color.color_purple));
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).
Add these to make changing text color simpler
myView.textColor = Color.BLACK // or Color.parseColor("#000000"), etc.
var TextView.textColor: Int
get() = currentTextColor
set(@ColorInt color) {
setTextColor(color)
}
myView.setTextColorRes(R.color.my_color)
fun TextView.setTextColorRes(@ColorRes colorRes: Int) {
val color = ContextCompat.getColor(context, colorRes)
setTextColor(color)
}