Android SwitchPreference 不工作

Android SwitchPreference not working

我正在尝试使用 SharedPreferences 检索 SwitchPreference 的值,但它不起作用。我正在使用 SwitchPreference 以便用户可以打开 on/off 通知,但无论值是什么,它都会显示通知。 这是代码。

NotificationUtils.java

SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
    if (preferences.getBoolean("notification_key", true)) {
        notificationManager.notify(NOTIFICATION_ID + rowId, notBuilder.build());
    }

preferences.xml

<SwitchPreference
    android:contentDescription="Turn notifications on/off"
    android:defaultValue="true"
    android:key="notification_key"
    android:summaryOff="Off"
    android:summaryOn="On"
    android:title="Notifications" />

我还在 SettingsFragment.java 中覆盖并注册了 OnSharedPreferenceChange 侦听器。

尝试替换

SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

PreferenceManager.getDefaultSharedPreferences(context);

我相信您正试图从错误的 SharedPreferences 中检索 "notification_key",这就是为什么它总是使用默认值 true 并显示您的通知。

编辑: 您可以使用 contains() 方法检查您正在使用的 SharedPreferences 是否包含 "notification_key" 键。

我解决了,实际上这个值没有切换,在设置屏幕上,开关是关闭和打开的,但该值仍然是默认值。通过在 OnPreferenceChangeListener 中设置新值解决了这个问题并且有效。