Talha
Talha

Reputation: 12717

Using Enums as Custom XML Attributes

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 !

Upvotes: 44

Views: 27062

Answers (2)

Sankar V
Sankar V

Reputation: 4872

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

Upvotes: 74

Adamlive
Adamlive

Reputation: 139

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.

Upvotes: 4

Related Questions