我想在设置首选项对话框中选择它后获取值。但是我得到ClassCastException
并且崩溃了?可能是因为我不确定如何获得已选择的值并将其保存。基本上我需要能够在另一个Activity
中获得新值。您如何获得这些价值并保存并能够在其他活动中找到它们?
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences s = getSharedPreferences("MY_PREFS", 0);
// Create a editor to edit the preferences:
SharedPreferences.Editor editor = s.edit();
if (key.equals("language_key")) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
ListPreference listPref = (ListPreference) sharedPreferences;
String entryvalue = (String) listPref.getEntry();
if (entryvalue == "EN")
{
Log.d(TAG, "EN" + entryvalue);
Toast.makeText(getBaseContext(), "true", Toast.LENGTH_SHORT).show();
}
else
{
Log.d(TAG, "else" + entryvalue);
Toast.makeText(getBaseContext(), "false", Toast.LENGTH_SHORT).show();
}
}
}
首选项xml文件
<ListPreference
android:key="language_key"
android:summary="Choice of language mode"
android:title="Language Mode"
android:defaultValue="CH"
android:entries="@array/Languages"
android:entryValues="@array/LanguageValues" />
array.xml
<string-array name="Languages">
<item name="EN">English</item>
<item name="CH">Chinese</item>
<item name="SP">Spanish</item>
</string-array>
<string-array name="LanguagesValues">
<item name="EN">EN</item>
<item name="CH">CH</item>
<item name="SP">SP</item>
</string-array>
答案 0 :(得分:1)
sharedPreferences
无法转换为ListPreferences。
要获取价值,请调用getString
方法:
sharedPreferences.getString( "language_key", "");