declare stylable enum code example

Example 1: define enum for customView

<attr name="myProperty" format="enum">
         <enum name="None" value="0"/>
         <enum name="One" value="1"/>
         <enum name="Two" value="2"/>
         <enum name="Three" value="3"/>
</attr>

Example 2: use enum in customview in android

inline fun <reified T : Enum<T>> TypedArray.getEnum(index: Int, default: T) =
    getInt(index, -1).let { if (it >= 0) enumValues<T>()[it] else default 
}

val a: TypedArray = obtainStyledAttributes(...)
val yourEnum: YourEnum = a.getEnum(R.styleable.YourView_someAttr, YourEnum.DEFAULT)
a.recycle()

Tags:

Misc Example