How to set default value for SwitchPreference in Android?
As I told, I write preferences programmatically:
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
PreferenceCategory catView = new PreferenceCategory(this);
catView.setTitle(R.string.preference_category_view);
root.addPreference(catView);
final SwitchPreference switchSplash= new SwitchPreference(this);
switchSplash.setKey(PreferenceKeys.SPLASH);
//-----the above code----
switchSplash.setChecked(false); // LINE 1
catView.addPreference(switchSplash); // LINE 2
While debugging I found that true
value is set in LINE 1, but when I add switchSplash
into catView
, the values of switchSplash
is reset to false
, because catView
sets values from preferences.xml.
That's why I changed all needed values into the XML
SharedPreferences.Editor editor = root.getPreferenceManager().getSharedPreferences().edit();
editor.putBoolean(PreferenceKeys.SPLASH, true);
editor.commit();