始终设置默认CheckBoxPreference

The*_*ter 2 android android-preferences

我有一个CheckBoxPreference,我希望默认检查它; 但它不起作用.

这是我的代码:

在我extends Application班上:

@Override
public void onCreate() {
    super.onCreate();

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.getBoolean("notify", true);

}
Run Code Online (Sandbox Code Playgroud)

而实际的Pref:

    <CheckBoxPreference
        android:key="notify"
        android:title="Push Notifications"
        android:summary="Receive status bar alerts"/>
    </PreferenceCategory>
Run Code Online (Sandbox Code Playgroud)

kev*_*ree 5

您需要将默认值添加到xml.请注意android:defaultValue="true"

机器人:默认值="真"

<CheckBoxPreference
    android:key="notify"
    android:title="Push Notifications"
    android:summary="Receive status bar alerts"
    android:defaultValue="true"
/>
Run Code Online (Sandbox Code Playgroud)