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?