#FF0000 I tried this...">

Get a color resource as a string

I am trying to use Color.parseColor() in a color resource:

 <color name="redish">#FF0000</color> 

I tried this, but it gives me an unknown color error :

 Color.parseColor(Integer.toHexString(context.getResources().getColor(R.color.redish))) 

How to correctly convert a color resource to String ?

+7
android android-xml android-resources
source share
5 answers

I think you missed #

 Color.parseColor("#"+Integer.toHexString(ContextCompat.getColor(context, R.color.redish))) 
+16
source share
 context.getResources().getColor(R.color.redish)); 
+2
source share

Updated answer:

 String colorHex = "#" + Integer.toHexString(ContextCompat.getColor(context, R.color.colorPrimary) & 0x00ffffff); 
+2
source share

 String colorString=getResources().getString(R.color.redish); 

try it

+1
source share

I got the color stored in the object (containing other fields). Colors were also defined in the xml file (colors.xml).
Therefore, I wanted to set the background color of the textview. I did it as follows:

 ... String color= res.colorName; // res is an object int c = context.getResources().getIdentifier(color,"color", context.getPackageName()); textView.setBackgroundColor(Color.parseColor("#" + Integer.toHexString(context.getResources().getColor(c)))); 

If you use the code in action, you can omit the use of "context".

0
source share

All Articles