dumazy dumazy - 1 year ago 69
Android Question

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

I have some colors defined in


How can I programmatically get the id of a certain color e.g.
if I know the name of the color.

Answer Source

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 ) {

    return colorId;

and in your case name is my_color:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download