【发布时间】:2016-12-09 20:45:15
【问题描述】:
我的活动中有一个ListPreference:
<ListPreference
android:key="pref_rValue"
android:entries="@array/r"
android:summary="***"
android:entryValues="@array/rValues"
android:title="Choose"
android:defaultValue="2"/>
其android:entries="@array/r" 和android:entryValues="@array/rValues" 在strings.xml 中分别定义如下:
<string-array name="r">
<item>0.5 km</item>
<item>1 km</item>
<item>2 km</item>
<item>5 km</item>
<item>10 km</item>
</string-array>
<string-array name="rValues">
<item>0.5</item>
<item>1.0</item>
<item>2.0</item>
<item>5.0</item>
<item>10.0</item>
</string-array>
在SettingActivity中定义的键:public static final String KEY_PREF_SYNC_CONN = "pref_rValue";
这是我如何使用密钥然后尝试在MainActivity 中获取此 ListPreference 的值:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String rValue = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "5");
Toast.makeText(getBaseContext(), "rValue: " + rValue, Toast.LENGTH_SHORT).show();
但是当我尝试将rValue 字符串用作Double 时,我收到了这个错误:java.lang.NumberFormatException: Invalid double: "2 km" 并且上面的 Toast 也显示了"rValue: 2 km"。
我想知道为什么不是从android:entryValues="@array/rValues" 获取价值,而是从android:entries="@array/r" 获取价值?
请帮我解决这个问题。
【问题讨论】:
-
您是否尝试过交换 XML 中的 android:entries 和 android:entryValues?
标签: java android sharedpreferences android-preferences listpreference