I have some colors defined in /values/colors.xml.
How can I programmatically get the id of a certain color e.g. R.color.my_color if I know the name of the color.
I have some colors defined in /values/colors.xml.
How can I programmatically get the id of a certain color e.g. R.color.my_color if I know the name of the color.
Try this:
public int getColorByName( String name ) {
int colorId = 0;
try {
Class res = R.color.class;
Field field = res.getField( name );
colorId = field.getInt(null);
} catch ( Exception e ) {
e.printStackTrace();
}
return colorId;
}
and in your case name is my_color:
getColorByName("my_color");
There is a dedicated method in Resources called getIdentifier.
It's the "normal" way of achieving what you search.
Try
final int lMyColorId = this.getResources().getIdentifier("my_color", "color", this.getPackageName());
where this is an Activity or any Context subclass reference. (Replace by getActivity() if needed.)
This is said to be slow but imo, this shouldn't be slower than accesing fields through the reflection mechanism the accepted answer suggests.
Example of use for some resource types are described here.
once you have the Context you can call getResources()-- to get Resources reference and thereafter query it to get both color and the id of the resource.
I found the accepted answer is not working as when I tried to set the background of an ImageView it was not setting the right color to it. But then I tried setting the background as resource and it worked perfectly.
So in case of any other confusions, I just want to copy the answer of @MarcinOrlowski and put all these together here.
So here's the function using reflection to get the resource id of the color.
public int getColorByName(String name) {
int colorId = 0;
try {
Class res = R.color.class;
Field field = res.getField(name);
colorId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
return colorId;
}
So now you can get the resource id simply by calling this.
int resourceId = getColorByName("my_color");
And while you're setting this color using the resource id you've got here, you need to do this.
myImageView.setBackgroundResource(resourceId);
I tried setting myImageView.setBackgroundColor(resourceId) which was not working.