obtainStyledAttributes无法找到数组

时间:2013-03-15 23:19:47

标签: android android-resources

我正在编写一个自定义DialogPreference,我使用2个名为条目 entryValues 的字符串数组设置首选项,类似于ListPreference需要的字符串。尽管在使用AttributeSet参数调用构造函数时,两个数组似乎都存在,但尝试通过obtainStyledAttributes获取样式化数组会因返回null而失败。

我做错了什么,我该如何解决这个问题?

我的自定义类代码是:

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>

1 个答案:

答案 0 :(得分:3)

带有+号的值对我来说很奇怪,我从未在我的设置中使用它们,也许这是行为不正确的主要原因。只需使用android:entries="@array/Backgrounds"而不使用+

还尝试使用我的代码获取值,至少它适用于整数类型的属性,所以它也适用于其他类型:

TypedArray a = context.obtainStyledAttributes(attrs, new int[] { R.attr.entries, R.attr.entryValues });
mEntries = a.getTextArray(0); // because R.attr.entries has index 0 in the passed array
mEntryValues = a.getTextArray(1);