3
我寫一個自定義的DialogPreference我設置有2個陣列命名項和entryValues,字符串的偏好相似什麼ListPreference需要。儘管當我的構造函數被AttributeSet參數調用時,這兩個數組似乎都存在,但試圖通過getsStyledAttributes獲取樣式化數組失敗,返回null。obtainStyledAttributes未能找到陣列
我在做什麼錯,我該如何解決這個問題?
我的自定義類的代碼是:
public class BackgroundPicker extends DialogPreference {
private CharSequence[] mEntries;
private CharSequence[] mEntryValues;
public BackgroundPicker(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Print all values in attrs AttributeSet:
for (int i=0;i<attrs.getAttributeCount();i++) {
String name = attrs.getAttributeName(i);
Object value = attrs.getAttributeValue(i);
Log.d(TAG, name + " : " + value + " of type " + value.getClass().getSimpleName());
}
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ListPreference, 0, 0);
// getIndexCount returns zero !
for(int i=0; i<a.getIndexCount(); i++) {
TypedValue v = a.peekValue(i);
Log.d(TAG, "value[" + i + "] = " + v.toString());
}
// Both entries and entryValues are null.
mEntries = a.getTextArray(R.styleable.ListPreference_entries);
mEntryValues = a.getTextArray(R.styleable.ListPreference_entryValues);
}
}
我調試打印是:
BackgroundPicker CTOR: IN
BackgroundPicker CTOR param attrs:
entries : @2131099650 of type String
title : @2131165247 of type String
key : BackgroundImage of type String
summary : @2131165248 of type String
defaultValue : back.png of type String
entryValues : @2131099651 of type String
BackgroundPicker CTOR param defStyle = 0
BackgroundPicker CTOR: OUT
我的風格在styles.xml
<declare-styleable name="ListPreference">
<attr name="entries" format="reference" />
<attr name="entryValues" format="reference" />
</declare-styleable>
我的數據arrays.xml
<array name="Backgrounds">
<item>back.png</item>
<item>one.png</item>
</array>
和我的喜好設置:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="@string/generaloptions" >
<BackgroundPicker
android:defaultValue="back.png"
android:entries="@+array/Backgrounds"
android:entryValues="@+array/Backgrounds"
android:key="BackgroundImage"
android:summary="@string/backgroundImageSummary"
android:title="@string/backgroundImage" />
</PreferenceCategory>
</PreferenceScreen>
不幸的是這並沒有解決這個問題。 getTextArray返回null。 a.getIndexCount()甚至返回null,儘管一個變量的長度爲2並且似乎有數據。我嘗試從條目的定義,其他獲取函數等中刪除android:現在,我正在提取引用的資源,unstyled並使用它(醜陋,我知道)。 – TudorT 2013-03-16 14:07:56
@TudoT實際上android已經有屬性'entries'和'entryValues',你不應該重新定義它們。也嘗試添加android命名空間到我的例子,如'android.R.attr.entries' – vorrtex 2013-03-16 17:52:24
非常感謝!使用android.R.attr.entries解決了這個問題。 PackageName.R.attr.entries不起作用。使用自定義名稱而不是「條目」和「entryValues」也不起作用。所以這是一個命名空間問題。 – TudorT 2013-03-16 23:22:39