androidcolorstextview

How to set the text color of TextView in code?


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?


Solution

  • You should use:

    holder.text.setTextColor(Color.RED);
    

    You can use various functions from the Color class to get the same effect of course.

    Check out the complete manual of course, public class Color extends Object.


    1This code used to be in here as well:

    textView.setTextColor(getResources().getColor(R.color.errorColor));
    

    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.