我想使用SharedPreferences检索SwitchPreference的值,但它不工作。我使用SwitchPreference,以便用户可以打开/关闭通知,但无论值是什么,它都会显示通知。 这是代码。Android 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注册的OnSharedPreferenceChange听众。
我已经使用了getDefaulSharedPreferences(context)方法,但是会发生同样的事情,如果键存在且返回true,则使用contains方法进行检查。当使用getBoolean方法时,无论布尔defValue我提供的是获取设置并显示通知,如果设置为true,无论交换机的状态如何,并且如果defValue设置为false,则即使开关状态为开,它也不会显示通知。我无法弄清楚那里发生了什么。 –