【问题标题】:Android SwitchPreference not workingAndroid SwitchPreference 不起作用
【发布时间】:2017-07-08 07:31:10
【问题描述】:

我正在尝试使用 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 中覆盖并注册了 OnSharedPreferenceChange 监听器。

【问题讨论】:

    标签: android sharedpreferences android-preferences android-sharedpreferences switchpreference


    【解决方案1】:

    尝试替换

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

    PreferenceManager.getDefaultSharedPreferences(context);
    

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

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

    【讨论】:

    • 我使用了 getDefaulSharedPreferences(context) 方法,但同样的事情发生了,如果键存在并且返回 true,则使用 contains 方法检查。使用 getBoolean 方法时,我提供的任何布尔 defValue 都会被设置并显示通知,如果设置为 true,无论开关的状态是什么,如果 defValue 设置为 false,那么即使开关状态打开,它也不会显示通知。我只是不知道那里发生了什么。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多