我很难理解如何保存ListPreference
作为整数的输入值。截至目前,我已经定义了我的ListPreference
如下:
<ListPreference
android:defaultValue="@string/list_preference_sorting_options_default_value"
android:title="@string/list_preference_sorting_options_title"
android:key="@string/list_preference_sorting_options_key"
android:entries="@array/list_preference_sorting_options_entries"
android:entryValues="@array/list_preference_sorting_options_entry_values"/>
... entries
和 entryValues
属性在以下数组中定义:
<array name="list_preference_sorting_options_entries">
<item>@string/list_preference_sorting_options_entry_popularity</item>
<item>@string/list_preference_sorting_options_entry_top_rated</item>
</array>
<array name="list_preference_sorting_options_entry_values">
<item>@string/list_preference_sorting_options_entry_value_popularity</item>
<item>@string/list_preference_sorting_options_entry_value_top_rated</item>
</array>
我知道我正在使用list_preference_sorting_options_entry_values
数组中的字符串值。但是,如果我要以不同的方式定义我的数组,例如:
<array name="list_preference_sorting_options_entry_values">
<item>0</item>
<item>1</item>
</array>
...然后在我的应用中,如果我尝试访问设置活动,我的应用程序会崩溃。
此外,如果我尝试将我的输入值读取为SharedPreferences
的INT(即使它们作为字符串存储)如下:
int methodFlag = preferences.getInt(getString(R.string.list_preference_sorting_options_key), 0);
...然后我收到一个Java错误,我无法将字符串投入int。为了正确获取入口值作为INT,我需要使用getString()
方法,然后将其解析为INT:
String preferenceMethodFlagString = preferences.getString(getString(R.string.list_preference_sorting_options_key),getString(R.string.list_preference_sorting_options_default_value));
int preferenceMethodFlag = Integer.parseInt(preferenceMethodFlagString);
我有没有办法通过arrays.xml直接存储整数值?如果我使用此实现(使用arrays.xml),我将始终必须将字符串解析为int?
我已经看过其他问题,所以问题如果使用SharedPreferences.Editor
,整数值将存储在ListPreference
的输入值中。这是存储整数值的唯一手段吗?
listPreference已经设计了以使其只能保持字符串值。
listPreference的成员变量如下
private CharSequence[] mEntries;
private CharSequence[] mEntryValues;
private String mValue;
private String mSummary;
此外,将值读取为
mEntries = a.getTextArray(com.android.internal.R.styleable.ListPreference_entries);
mEntryValues = a.getTextArray(com.android.internal.R.styleable.ListPreference_entryValues);
getTextArray()仅查找字符串阵列资源ID。
因此,条目和输入值应始终是字符串资源。
如果要使用int值,
<string-array name="entries_list_preference">
<item>0</item> <!-- This does not make it int, it will be stored as string only -->
<item>1</item>
<item>2</item>
</string-array>
<string-array name="entryvalues_list_preference">
<item>0</item>
<item>1</item>
<item>2</item>
</string-array>
当您阅读其价值时,将其解析为整数。
ListPreference listPreference = (ListPreference) findPreference ("list_preference");
String value = listPreference.getValue();
if(!TextUtils.isEmpty(value))
performAction(Integer.parseInt(listPreference.getValue()));
现在您可以根据您的要求编写表演(int类型)方法。
你做不到。Android仅将字符串数组用于条目和条目值。但是您可以使用Integer.parseInt()
方法轻松地将字符串转换为INT。希望这会有所帮助。