我正在settings.xml文件中使用ListPreference。我想向用户显示一个包含3个选项的列表。当用户在设置中选择其中一个选项时,我收到以下错误:
java.lang.NullPointerException
at android.preference.ListPreference.onDialogClosed(ListPreference.java:264)
at android.preference.DialogPreference.onDismiss(DialogPreference.java:381)
at android.app.Dialog$ListenersHandler.handleMessage(Dialog.java:1228)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
这是ListPreference的代码:
<ListPreference
android:entries="@array/date_alignement"
android:entryValues="@array/date_alignement_values"
android:key="settings_date_alignement"
android:summary="@string/settings_date_alignement_summary"
android:title="@string/settings_date_alignement_title" />
下面是我用来填充条目的数组:
<string-array name="date_alignement">
<item>"Top"</item>
<item>"Center"</item>
<item>"Bottom"</item>
</string-array>
<integer-array name="date_alignement_values">
<item >0</item>
<item >1</item>
<item >2</item>
</integer-array>
在我的onSharedPreferenceChanged中,我以如下方式使用这些值:
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
//Text
mAlignment = mPrefs.getInt(PREF_ALIGNMENT, 1);
switch (mAlignment) {
case 0:
offsetY = mHeight/3.0f;
break;
case 2:
offsetY = mHeight*2.0f/3.0f;
break;
default:
offsetY = mHeight/2.0f;
break;
}
}
如果我用另一个字符串数组来表示entryValues,它就可以工作,例如,如果我用同一个字符串数组作为值和条目:
android:entries="@array/date_alignement"
android:entryValues="@array/date_alignement"
然后我需要稍微修改一下代码,但它还是有效的
if(mAlignment.equalsIgnoreCase("center")) {
offsetY = mHeight/2.0f;
} else if(mAlignment.equalsIgnoreCase("top")) {
offsetY = mHeight/3.0f;
} else if(mAlignment.equalsIgnoreCase("bottom")) {
offsetY = mHeight*2.0f/3.0f;
}
为什么我不能使用字符串数组和整数数组作为ListPreference的条目和值?
4条答案
按热度按时间mbzjlibv1#
答案很简单:因为Android就是这样设计的。它只使用
String
数组来表示条目和条目值,仅此而已。我看不出这有什么问题,因为你可以很容易地使用Integer.parseInt()
方法将String
转换为int
。41ik7eoe2#
您可以将输入值转换为字符串以使
ListPreference
满意,然后在与持久数据存储器通信时将其转换为int
。1.设置条目值时,请使用字符串而不是整数:
"1", "2", "3"
等1.创建一个定制的
IntListPreference
,将这些值作为整数保存1.在
preferences.xml
文件中,将<ListPreference>
更改为<your.app.package.IntListPreference>
IntListPreference.java
这是一个示例实现,已在AndroidX Preference 1.0.0上测试并运行。
e0bqpujr3#
答案在列表首选项文档中列出。
将返回给定值的索引,并且参数被视为String,因此entryValues数组应该是字符串数组才能完成此工作。
v1uwarro4#
以下几点对我很有效: