How to set the color of a TextView in Android?

Android

Android Problem Overview


In the string.xml file I use the following tag

<color name="mycolor1">#F5DC49</color>

If I use

 textview1.setTextColor(Color.CYAN);

it works, but

 textview1.setTextColor(R.color.mycolor1);

is not working.

How can I use the color defined in the XML file?

Android Solutions


Solution 1 - Android

TextView.setTextColor() takes an int representing the color (eg. 0xFFF5DC49) and not the resource ID from the xml file. In an activity, you can do something like:

   textView1.setTextColor(getResources().getColor(R.color.mycolor))

outside of an activity you'll need a Context eg.

   textView1.setTextColor(context.getResources().getColor(R.color.mycolor))

Solution 2 - Android

 textView1.setTextColor(Color.parseColor("#F5DC49"));

without resources

Solution 3 - Android

context.getResources().getColor is Deprecated.

You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).

ContextCompat.getColor(context, R.color.my_color);

You will need to add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:

compile 'com.android.support:support-v4:23.0.1' # or any version above

If you care about theming, the documentation specifies that the method will use the context's theme:

> Starting in M, the returned color will be styled for the specified > Context's theme

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArunView Question on Stackoverflow
Solution 1 - AndroidPatrick CullenView Answer on Stackoverflow
Solution 2 - AndroidAnilPatelView Answer on Stackoverflow
Solution 3 - AndroidPratik ButaniView Answer on Stackoverflow