dumazy dumazy - 2 months ago 5
Android Question

How do I get a color id with a known color name

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.

Answer

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");
Comments