2013-08-22 129 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

與解釋自述希望它能幫助。