问题
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 "slider" which you can move to on or off...hope you understand what I mean). The user sets switch to ON then closes the app and reopens it and the switch is off...but it shouldn't be off...it should be on, like the user sets it How can I do that? The switch should save its state, how the user selects it Do I need mysql or something?
I hope you understand what I mean
Thanks
回答1:
you should use SharedPreferences like so:
public static final String SWITCH_PREFS = "Switcher";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Switch switcher = (Switch)findViewById(R.id.yourSwitchId);
switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(yourContext).edit();
editor.putBoolean(SWITCH_PREFS,isChecked);
editor.commit();
}
});
SharedPreferences prefs = 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.
来源:https://stackoverflow.com/questions/24888575/android-studio-how-can-i-let-switch-be-checked-after-restarting-the-app