How to get an enum which is created in attrs.xml in code

后端 未结 5 1842
小蘑菇
小蘑菇 2020-12-23 20:30

I created a custom View (find it here) with an declare-styleable attribute of type enum. In xml I can now choose one of the enum entries for my custom attribute. Now I want

5条回答
  •  死守一世寂寞
    2020-12-23 20:32

    Let me add a solution written in kotlin. Add inline extension function:

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

    Now getting enum is simple:

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

提交回复
热议问题