我试图使用SharedPreferences检索SwitchPreference的值,但它不起作用。我使用SwitchPreference,这样用户就可以打开/关闭通知,但是它会显示通知,而不管它的值是什么。这是密码。
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中重写和注册了SettingsFragment.java侦听器。
发布于 2017-07-09 06:38:34
我解决了它,实际上这个值不是切换的,在设置屏幕上开关是关闭的,但是这个值仍然是默认的。通过在OnPreferenceChangeListener中设置新值来解决这个问题,这是可行的。
发布于 2017-07-08 07:43:16
试着替换
SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);使用
PreferenceManager.getDefaultSharedPreferences(context);我相信您正在尝试从错误的"notification_key"中检索SharedPreferences,这就是为什么它总是使用true的默认值并显示通知。
编辑:您可以检查使用的SharedPreferences是否包含contains()方法的"notification_key“键。
https://stackoverflow.com/questions/44983709
复制相似问题