Android Studio - How Can I Let Switch Be Checked After Restarting The App
I only have a switch toggle on my fragment. What is the app doing now: The user opens the app and selects 'Laptop' over the navigation drawer and then he sees a switch (it is a 'sl
Solution 1:
you should use SharedPreferences like so:
publicstaticfinalStringSWITCH_PREFS="Switcher";
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Switchswitcher= (Switch)findViewById(R.id.yourSwitchId);
switcher.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener() {
@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editoreditor= PreferenceManager.getDefaultSharedPreferences(yourContext).edit();
editor.putBoolean(SWITCH_PREFS,isChecked);
editor.commit();
}
});
SharedPreferencesprefs= PreferenceManager.getDefaultSharedPreferences(yourContext);
if(prefs.contains(SWITCH_PREFS) && switcher != null)
{
switcher.setChecked(prefs.getBoolean(SWITCH_PREFS,false));
}
}
Didn't try this code, but hope this works.
Post a Comment for "Android Studio - How Can I Let Switch Be Checked After Restarting The App"