2013-08-22 79 views
65

attrs.xml中创建的枚举我使用enum类型的declare-styleable属性创建了自定义View(查找它here)。在xml中,我现在可以为我的自定义属性选择其中一个枚举条目。现在我想创建一个方法来以编程方式设置此值,但我无法访问枚举。如何获得在代码

attr.xml

<declare-styleable name="IconView"> 
    <attr name="icon" format="enum"> 
     <enum name="enum_name_one" value="0"/> 
     .... 
     <enum name="enum_name_n" value="666"/> 
    </attr> 
</declare-styleable>  

layout.xml

<com.xyz.views.IconView 
    android:id="@+id/heart_icon" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    app:icon="enum_name_x"/> 

我需要的是这样的:mCustomView.setIcon(R.id.enum_name_x); 但我找不到枚举或我甚至不知道我如何获得枚举或枚举的名称。

感谢

回答

63

似乎没有成为一个自动化的方式来获得属性枚举一个Java枚举 - 在Java中,你可以得到你所指定的数值 - 该字符串是在XML文件中使用(如您显示)。如果你想要的值到一个枚举你需要的值或者是映射到Java枚举自己,如

TypedArray a = context.getTheme().obtainStyledAttributes(
       attrs, 
       R.styleable.IconView, 
       0, 0); 

    // Gets you the 'value' number - 0 or 666 in your example 
    if (a.hasValue(R.styleable.IconView_icon)) { 
     int value = a.getInt(R.styleable.IconView_icon, 0)); 
    } 

    a.recycle(); 
} 

private enum Format { 
    enum_name_one(0), enum_name_n(666); 
    int id; 

    Format(int id) { 
     this.id = id; 
    } 

    static Format fromId(int id) { 
     for (Format f : values()) { 
      if (f.id == id) return f; 
     } 
     throw new IllegalArgumentException(); 
    } 
} 

你可以在你看来构造做到这一点

然后在第一个代码块,你可以使用:

Format format = Format.fromId(a.getInt(R.styleable.IconView_icon, 0))); 

(尽管在该p抛出异常oint可能不是一个好主意,可能更适合选择合理的默认值)

7

为了理智的缘故。确保你的序号在声明样式中与你的Enum声明中的相同,并以数组的形式访问它。

TypedArray a = context.getTheme().obtainStyledAttributes(
        attrs, 
        R.styleable.IconView, 
        0, 0); 

int ordinal = a.getInt(R.styleable.IconView_icon, 0); 

if (ordinal >= 0 && ordinal < MyEnum.values().length) { 
     enumValue = MyEnum.values()[ordinal]; 
} 
+0

我认为在这里依赖枚举序列注定要创建不可靠的代码。有一件事会得到更新,而不是其他的,然后你会遇到麻烦。 – tir38

2

我知道这个问题发布后已经有一段时间了,但最近我有同样的问题。我使用Square的JavaPoet和build.gradle中的一些东西一起攻击了一些东西,这些东西在项目构建中自动从attrs.xml创建Java枚举类。

有一个小的演示,并在https://github.com/afterecho/create_enum_from_xml

与解释自述希望它能帮助。