2010-03-17 34 views
4

我已經使用edittext和微調控件創建了組合框控件。 我想讓android:prompt屬性傳遞到 微調器,這意味着我需要在構造函數中捕獲它,其中 將AttributeSet設置爲傳遞給我的AttributeSet並將其設置在微調器上。 我無法弄清楚如何獲得提示的值。 我想,如何檢索自定義控件的XML屬性

int[] ra = { android.R.attr.prompt }; 
TypedArray ta = context.getTheme().obtainStyledAttributes(ra); 
int id = ta.getResourceId(0, 0); 

我回來0,這意味着它沒有找到該屬性。 我也做了ta.count()返回0.所以我沒有得到任何回報。

我的XML只是定義了一個android:提示值。

感謝

回答

6

我剛寫了一個答案,解釋了整個using XML with custom UI elements的過程。在你的情況下,不需要聲明一個可修改的樣式,因爲你不需要自定義屬性。使用android.R.attr.prompt作爲int id將正常工作。 R.styleable.className_attributeName只有在您定義了樣式中的屬性後才能起作用,並且您通過將R.styleable.className傳入obtainStyledAttributes來檢索它們。

0
  1. 定義的XML風格。對於前: <declare-styleable name="ComboBox"> <attr name="prompt" format="reference"/> </declare-styleable>

  2. 在構造函數中使用獲得的價值: TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ComboBox);

使用TypedArray get方法來獲取特定屬性。

+0

這個,但你不應該忘記在佈局xml:xmlns:app =「http://schemas.android.com/apk/res/package.name」中爲你的自定義設置定義一個新的xml命名空間。並使用a.getString(R.stylable.option_name)來獲得選項。 – MrSnowflake 2010-03-17 09:46:21

+1

非常感謝! a.getString(R.styleable.option_name)不起作用。我得到一個索引越界異常。我認爲索引應該是數組中的索引,而不是資源ID。 使用android:prompt也可以,android.R.attr.prompt。 我的問題是在getsStyleAttributes方法上使用了錯誤的簽名。我以爲我必須使用主題。這些簽名的工作原理如下: TypedArray a = context.obtainStyledAttributes(attrs,new int [] {android.R.attr.prompt}); 或 context.obtainStyledAttributes(attrs,new int [] {android.R.attr.prompt},0,0); 然後 a.getResourceId(0,0); – David 2010-03-17 14:55:38