Using Enums as Custom XML Attributes
25,029
Solution 1
Ex :
<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>
Use like this:
<YourCustomView
...
app:myProperty="One"/>
Reference
https://stackoverflow.com/a/15231645/1329126
Solution 2
Order inside the XML matters, at least to eclipse. Define your enum above (or inside) your declare-styleable... not below.
<attr name="quality">
<enum name="Good" value="1" />
<enum name="Better" value="2" />
<enum name="Best" value="3" />
</attr>
<declare-styleable name="SquareView">
<attr name="quality" />
</declare-styleable>
<declare-styleable name="CircleView">
<attr name="quality" />
</declare-styleable>
I had a very long enum so I placed it at the end of my XML to improve readability. It would parse correctly but reject values in Design mode.
Author by
Talha
Currently, I'm deep into writing clean, maintainable and testable Android code, using Kotlin, RxJava, Clean-MVP and MVI architecture, Dagger2.
Updated on July 09, 2022Comments
-
Talha almost 2 years
I want to use custom components in my project and i want to add it to enum attributes like below , how can i do that ?
<com.abb.abbcustomcompanents.buttons.AbbButton android:id="@+id/abbBtn1" android:layout_width="wrap_content" android:layout_height="wrap_content" app:Type="How can i use enum here" /> <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="abbButton"> <attr name="Type" format="enum"/> <attr name="onAction" format="string"/> </declare-styleable> </resources>
Thank you !
-
Neon Warge over 7 yearsHow do I get this on my custom view?
-
droppin_science about 7 years@NeonWarge A bit late I know but for future I've add a use case