从 ListPreference 获取键值

Get keyValue from ListPreference

以下问题:

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"/>

我的问题是,如何获取值(123)以在我的 if 条件下使用它MainActivity.java

    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)

设置活动:

@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 playSound = sharedConfig.getBoolean("sound_on_create", false);
    boolean vibrate = sharedConfig.getBoolean("vibrate_on_create", false);

更新:

我只需要删除缓存和内存...

尝试使用 getBaseContext():

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()) ;

试试这个

if(removeonklick == "3")
{}

首先,这一行应该放在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
   }