Android switchpreference如何设置交换机首选项默认值?

Android switchpreference如何设置交换机首选项默认值?,android,android-preferences,Android,Android Preferences,我有一个开关偏好,并希望它被默认为“开”。。。 在xml中 <SwitchPreference android:defaultValue="true" android:key="PromoNotificationOnOff" android:title="@string/Snotification_enable" /> 为什么不起作用?少了什么?谢谢 在您的MainActivity onCreate方法中添加此行 Preference

我有一个开关偏好,并希望它被默认为“开”。。。 在xml中

<SwitchPreference
        android:defaultValue="true"
        android:key="PromoNotificationOnOff"
        android:title="@string/Snotification_enable" />

为什么不起作用?少了什么?谢谢

在您的
MainActivity onCreate
方法中添加此行

PreferenceManager.setDefaultValues(this, R.xml.settings, false);  

您可以在,int,boolean)上了解它。

代码是正确的,只需使用switchPreferenceCompact而不是SwitchPreference

     <SwitchPreferenceCompat
        app:key="promoNofitficationOnOff"
        app:summaryOff="@string/notification_summary_off"
        app:summaryOn="@string/notification_summary_on"
        app:defaultValue="true"
        app:title="@string/promo_notification_title" />


XML“android:defaultValue”标记绝对正确。更新代码中的值(覆盖它)是多余的,如果两者都保留在原位,可能会导致以后的混淆。但是,调试此代码时,在Android设置中清除应用程序数据之前,首选项的“默认值”通常不会生效。@gtcompscientist在您进行评论和否决表决之前,您应该阅读参考链接。如果这太麻烦了,那么您至少应该阅读setDefaultValues()上的文档,以了解参数代表什么。在我提供的更新xml中的值集的解决方案中的哪里?如果你知道setDefaultValues()方法是什么,那么我提供的解决方案是绝对正确和清晰的。gtcompscientist的评论被多次向上投票可能会误导现在阅读它的任何人。正如Hoan Nguyen所指出的,
setDefaultValues()
方法使用首选项xml中的默认值。它不会覆盖已经设置的首选项,即使readreach参数设置为“true”(如果只有很少的条目,可能更好)。这仍然适用于新的androidx首选项库。答案是正确的。
     <SwitchPreferenceCompat
        app:key="promoNofitficationOnOff"
        app:summaryOff="@string/notification_summary_off"
        app:summaryOn="@string/notification_summary_on"
        app:defaultValue="true"
        app:title="@string/promo_notification_title" />