从 SharedPreferences 中读取一个布尔值

Read an boolean from SharedPreferences

我想检查来自 SettingsActivity.java

的 SwitchPrefernce/CheckBoxPreference 的布尔值 (true/false)

在MainActivity中是如下代码:

    SharedPreferences notification1, notification2, notification3;
    notification1 = getSharedPreferences("sound_on_create", Context.MODE_PRIVATE);
    notification2 = getSharedPreferences("vibrate_on_create", Context.MODE_PRIVATE);
    notification3 = getSharedPreferences("remove_onklick", Context.MODE_PRIVATE);
    boolean playSound = notification1.getBoolean("sound_on_create", false);
    boolean vibrate = notification2.getBoolean("vibrate_onklick", false);
    boolean removeOnklick = notification3.getBoolean("remove_onklick", true);

以及SettingsActivity中的定义:

     <SwitchPreference
        android:title="Text 1"
        android:summary="summary 1"
        android:key="sound_on_create"
        android:defaultValue="true"/>

    <SwitchPreference
        android:title="Text 2"
        android:summary="summary 2"
        android:key="vibrate_on_create"
        android:defaultValue="true"/>

    <SwitchPreference
        android:title="Text 3"
        android:summary="summary 3"
        android:key="remove_onclick"
        android:defaultValue="true"/>

如果我用 Log.d 得到值,这些值总是 false false true 那么,如何获取用户可以在设置中设置的值呢?

如果您要从首选项 xml 文件中保存首选项,您需要使用:

getDefaultSharedPreferences(this)

而不是

getSharedPreferences("sound_on_create", Context.MODE_PRIVATE);

编辑:打字错误

您似乎在使用 PreferenceActivity,因此这些值将存储在您应用的默认 SharedPreferences 中。

您当前的代码正在查看三个单独的首选项文件(SharedPreferences 存储在 xml 文件中)。

与其查找值不存在的三个文件,不如从默认的 SharedPreferences 文件中获取它们,它们确实存在于该文件中:

    SharedPreferences sharedPrefs =  PreferenceManager.getDefaultSharedPreferences(this);
    boolean playSound = sharedPrefs.getBoolean("sound_on_create", false);
    boolean vibrate = sharedPrefs.getBoolean("vibrate_on_create", false);
    boolean removeOnklick = sharedPrefs.getBoolean("remove_onclick", true);

    //testing:
    Toast.makeText(this, "values: " + playSound + " " + vibrate + " " + removeOnklick, Toast.LENGTH_LONG).show();