Re-using Android Custom enum xml attributes

时光毁灭记忆、已成空白 提交于 2019-12-03 04:52:26

问题


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>

回答1:


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>


来源:https://stackoverflow.com/questions/15231191/re-using-android-custom-enum-xml-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!