[英]How to get the “title” instead of the “value” of a preference with getString()
[英]sharedPref.getString() picking value from ListPreference's entries instead of entryValues
我的活動中有一個ListPreference
:
<ListPreference
android:key="pref_rValue"
android:entries="@array/r"
android:summary="***"
android:entryValues="@array/rValues"
android:title="Choose"
android:defaultValue="2"/>
在strings.xml
分別定義其android:entries="@array/r"
和android:entryValues="@array/rValues"
,如下所示:
<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
定義的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"
取值?
請幫我解決這個問題。
這是一個非常簡單而愚蠢的問題。
我剛剛卸載了該應用程序,然后再次安裝,一切正常。
但是,我很想知道如何確保以后不會再發生這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.