Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create enum of colors (int) from android resource colors.xml

I am trying to access xml colors into an enum. Since I don't have access to context. I am lost on how to access colors from resources.

The colors can be in any form (they can be retrived as an int or color)

So far, I have something like this

enum class NotificationType(val color: Int){
    //    DANGER("#F97068"),
    //    WARNING("#D1D646"),
    //    INFO("#BEBEBE"),
    //    SUCCESS("#76D13A")
}
like image 980
Raj Rajput Avatar asked Oct 21 '25 11:10

Raj Rajput


1 Answers

You can use the int color resources instead of the hex representation:

enum class NotificationType(val color: Int) {
    DANGER(R.color.danger), 
    WARNING(R.color.warning), 
    INFO(R.color.info), 
    SUCCESS(R.color.success);
}

colors.xml:

<resources>
    <color name="danger">#F97068</color>
    <color name="warning">#D1D646</color>
    <color name="info">#BEBEBE</color>
    <color name="success">#76D13A</color>
</resources>

UPDATE:

Nice tip by @Tenfour04, you can add a utitlity method to get the color from some enum value:

enum class NotificationType(val color: Int) {
    DANGER(R.color.danger),
    WARNING(R.color.warning),
    INFO(R.color.info),
    SUCCESS(R.color.success);

    fun toArgb(context: Context) =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            context.resources.getColor(color, null)
        else
            context.resources.getColor(color) // Deprecated in API level 23
}

Usage:

val color = NotificationType.DANGER.toArgb(context)
like image 169
Zain Avatar answered Oct 23 '25 08:10

Zain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!