以下问题:
preferences.xml
:
<ListPreference
android:title="titel"
android:summary="summary"
android:key="remove_onclick"
android:entries="@array/removeOnclick"
android:entryValues="@array/removeOnclick_value"
android:defaultValue="3"/>
我的问题是,如何获取值(1
、2
或 3
),以便在 MainActivity.java 中将其与 if 条件一起使用
SharedPreferences sharedConfig = PreferenceManager.getDefaultSharedPreferences(this);
String removeOnklick = sharedConfig.getString("remove_onclick", "3");
这不起作用!
Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String at com.notification.app.SettingsActivity.onCreate(SettingsActivity.java:14)
设置 Activity :
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}
编辑
strings.xml
<string-array name="removeOnclick">
<item>Always</item>
<item>Never</item>
<item>Always ask</item>
</string-array>
<string-array name="removeOnclick_value">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
而且我还有 2 个可以完美工作的 boolean 值。
boolean playSound = sharedConfig.getBoolean("sound_on_create", false);
boolean vibrate = sharedConfig.getBoolean("vibrate_on_create", false);
更新:
我只需删除缓存和内存...
最佳答案
首先,这一行应该放在 MainActivity 的 onCreate 方法中:
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
并且,要从 SettingsActivity 中的 ListPreference 获取值:
ListPreference pref = findPreference("remove_onclick");
String value = pref.getValue();
if (value.equals("3")){
// do something here with value 3
}
如果你想从MainActivity获取值,调用:
SharedPreferences sharedConfig = PreferenceManager.getDefaultSharedPreferences(this);
String removeOnklick = sharedConfig.getString("remove_onclick", "3");
if(removeOnklick.equals("1"){
// do something here with value 1
}
关于java - 从ListPreference中获取keyValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31139130/