Search code examples
androidstringcolorsandroid-resources

Possible to get color with string?


In my values folder I have my_colors.xml:

<resources>
    <!-- Orange -->
    <color name="orangePrimary">#f6a02d</color>
    <color name="orange1">#e3952a</color>
    <color name="orange2">#da8f28</color>
    <color name="orange3">#d08926</color>
</resources>

Is there a way to get these colors just with the string of its name? Something like view.setBackgroundColor.getColor("orange1");

For images you have this getResources().getIdentifier("my_image", "drawable", getPackageName());

Hope you guys know what I mean. Greetings.


Solution

  • Have you tried the following:

    // java
    Resources res = context.getResources();
    String packageName = context.getPackageName();
    
    int colorId = res.getIdentifier("my_color", "color", packageName);
    int desiredColor = res.getColor(colorId);
    
    // kotlin
    val res: Resources = context.getResources()
    val packageName: String = context.getPackageName()
    
    val colorId: Int = res.getIdentifier("my_color", "color", packageName)
    val desiredColor: Int = res.getColor(colorId)
    

    Hope it helps!


    Note: This is deprecated, instead you could do the following, which handles both pre and post Marshmallow (API 23):

    // java
    Resources res = context.getResources();
    String packageName = context.getPackageName();
    
    int colorId = res.getIdentifier("my_color", "color", packageName);
    int desiredColor = ContextCompat.getColor(context, colorId);
    
    // kotlin
    val res: Resources = context.getResources()
    val packageName: String = context.getPackageName()
    
    val colorId: Int = res.getIdentifier("my_color", "color", packageName)
    val desiredColor: Int = ContextCompat.getColor(context, colorId)