28

I'm defining a custom attribute in XML that is an enum.It looks something like this:

<declare-styleable name="MyControl">
    <attr name="myProperty">
        <enum name="None" value="0"/>
        <enum name="One" value="1"/>
        <enum name="Two" value="2"/>
        <enum name="Three" value="3"/>
        <enum name="Four" value="4"/>
        <enum name="Five" value="5"/>
        <enum name="Six" value="6"/>
        <enum name="Seven" value="7"/>
        <enum name="Eight" value="8"/>
        <enum name="Nine" value="9"/>
        <enum name="Ten" value="10"/>
    </attr>
</declare-styleable>

Suppose now that I want another, unrelated class to use this same set of enum values. Is there a way to do this without resorting to making a copy of the list of enums in the new in the new node?. For instance, something with semantics of something like this:

 <declare-styleable name="MyUnrelatedControl">
    <attr name="myProperty" format="[myEnum Format Reference]"/>
 </declare-stylable>
ptoinson
  • 2,013
  • 3
  • 21
  • 30

1 Answers1

56

Just define the attribute outside of your control:

<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"/>
    <enum name="Four" value="4"/>
    <enum name="Five" value="5"/>
    <enum name="Six" value="6"/>
    <enum name="Seven" value="7"/>
    <enum name="Eight" value="8"/> 
    <enum name="Nine" value="9"/>
    <enum name="Ten" value="10"/>
</attr>

Then just reuse that for all of your controls:

<declare-styleable name="MyControl">
    <attr name="myProperty"/>
</declare-styleable>

<declare-styleable name="MyUnrelatedControl">
    <attr name="myProperty"/>
</declare-styleable>
Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • 5
    Perfect. Thank You. Perhaps you will know if there is a way to do this with two different attributes in the same object with the same enum. For example my class has both the attributes _myProperty and _myOtherProperty which can both have the same enum value? – ptoinson Mar 05 '13 at 19:00
  • 4
    That's a great question. Unfortunately, I don't know of a way to do that, although it seems like something that should exist. Might be worth looking into the Android source for how they define `layout_width` and `layout_height`, or something like that, as I imagine they would reuse `wrap_content` and `match_parent`. – Kevin Coppock Mar 05 '13 at 19:04
  • 3
    From looking at the Android source, they define them every time, so I'm assuming there's probably no way to simplify it any further. – Kevin Coppock Mar 05 '13 at 21:44
  • I have additional requirement here, The is from Java file also like ellipsize then how to use this I want to access that enum in java file Can we do the same for ellipsize for edittext??? – Sushant Gosavi Dec 26 '19 at 14:32