【问题标题】:Using Enums as Custom XML Attributes使用枚举作为自定义 XML 属性
【发布时间】:2013-04-11 08:12:38
【问题描述】:

我想在我的项目中使用自定义组件,我想将它添加到枚举属性中,如下所示,我该怎么做?

<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>

谢谢!

【问题讨论】:

标签: android android-layout android-custom-view


【解决方案1】:

例如:

<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>

这样使用:

<YourCustomView
    ...
    app:myProperty="One"/>

参考

https://stackoverflow.com/a/15231645/1329126

【讨论】:

  • 如何在我的自定义视图中获取此信息?
  • @NeonWarge 我知道有点晚了,但我已经添加了一个用例
【解决方案2】:

XML 内部的顺序很重要,至少要黯然失色。在您可声明样式的上方(或内部)定义您的枚举...而不是下方。

<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>

我有一个很长的枚举,所以我把它放在我的 XML 的末尾以提高可读性。它会正确解析,但在设计模式下会拒绝值。

【讨论】:

    猜你喜欢
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2020-07-19
    • 2016-12-11
    • 1970-01-01
    相关资源
    最近更新 更多