'Synchronising attrs.xml enum and kotlin enum class
So, in my attrs.xml i have an enum attribute like this:
<attr name="direction">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
<enum name="both" value="2" />
</attr>
<declare-styleable name="CustomPicker">
<attr name="direction"/>
...
</declare-styleable>
then in my custom view class I have this property which I set in the constructor with the attribute's value. The int value that the attribute gives is converted to an enum class value, which I can then use in the rest of the view's code:
enum class Direction(val value: Int) {
HORIZONTAL(0),
VERTICAL(1),
BOTH(2);
companion object {
fun fromValue(value: Int): Direction = values().first { it.value == value}
}
}
private var mDragDirection: Direction = Direction.HORIZONTAL
var direction: Int
set(value) { mDragDirection = Direction.fromValue(value) }
get() { return mDragDirection.value }
So the problem is that I'm defining the same thing separately in two different places. If I were to make any change to one, I would have to remember to update the other. Obviously I could just use integers in my kotlin code instead of an enum, but then I'd have a bunch of magic numbers in if and when statements, and that's not good either.
Is it possible to derive the enum class from the attribute enum, or vice versa? I'd like some way that I only have to define the enum once, and it's values are propagated to both the attribute and the code-behind.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
