0

I have an enum in my Kotlin app:

enum class MeasurementUnits(val displayString: String) {
    KILOGRAM("kg"),
    POUND("lbs"),
    KILOMETER("km"),
    MILE("mi"),
}

I'd like to use this enum in a custom attribute in a compound View I'm writing, like so:

<com.myapp.MyCustomView
    android:id="@+id/distance"
    custom:display_units="KILOMETER" />

But the only way I see of defining this attribute as an enum is separate and unrelated to the enum, in attrs.xml:

<attr name="input_units" format="enum">
   <enum name="KILOGRAM" value="0"/>
   <enum name="POUND" value="1"/>
   <enum name="KILOMETER" value="2"/>
   <enum name="MILE" value="3"/>
</attr>

This is weird, since I'm re-defining the enum again, and it's super fragile - they must be completely in sync, any changes must be done in the same place. I don't want to just write it as string since this is super fragile too, but it's slightly better - at least I don't force the order to be the same.

Is there a way to define a custom enum attribute, and point to the enum class in my code? Or at least make sure the lists are in sync?

What's the best practice here?

Yossi Vainshtein
  • 3,845
  • 4
  • 23
  • 39
  • Take a look at this: https://stackoverflow.com/a/58815613/8084314 – MoeinDeveloper Jul 30 '21 at 20:19
  • @MoeinDeveloper Yes I saw that, thanks. Getting the value of the enum is easier, but I still have to maintain 2 identical lists in my code, and if god forbid one is changed and the other is not, I'm screwed – Yossi Vainshtein Jul 30 '21 at 20:30
  • Seems like there's no other way, Check Lottie's enum: https://github.com/airbnb/lottie-android/blob/master/lottie/src/main/res/values/attrs.xml – MoeinDeveloper Jul 30 '21 at 20:36
  • I just found this repo on github, I thought it might be usefull to you: https://github.com/afterecho/create_enum_from_xml – MoeinDeveloper Aug 01 '21 at 09:11

0 Answers0