Search code examples
androidandroid-preferences

Android switchpreference how can i set the switch preference default value?


I have a switch preference and want it to be defaulted "ON"... in the xml,

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

and in class,

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.settings);


}

why isn't it working? What is missing? Thanks!!


Solution

  • In your MainActivity onCreate method add this line

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

    You can read about it at http://developer.android.com/reference/android/preference/PreferenceManager.html#setDefaultValues(android.content.Context, int, boolean)