Re-using Android Custom enum xml attributes

ptoinson picture ptoinson · Mar 5, 2013 · Viewed 12.7k times · Source

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>

Answer

Kevin Coppock picture Kevin Coppock · Mar 5, 2013

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>