问题
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?
(By the way, I am using Android Studio)
I hope you understand what I mean
Thanks
回答1:
try using shared preferences to save application data, Application can save data in share preferences when application start again it can load data from shared preferences again ... hope it help :)
回答2:
You should use SharedPreferences
to save the data captured by the Switch
. Try the following.
(in your onViewCreated after you initialize your other stuff)
Switch mySwitch = (Switch) findViewById(R.id.mySwitch); // or however else you want to initialize it
final String SWITCH_BOOLEAN = "switchBoolean";
final String PREFERENCE_NAME = "sharedPreferenceFile";
final SharedPreferences prefs = getActivity().getSharedPreferences(PREFERENCE_NAME, 0); // change the name to what you want, this is an xml file that stores your preferences
final SharedPreferences.Editor prefsEditor = prefs.getEditor();
mySwitch.setChecked(prefs.getBoolean(SWITCH_BOOLEAN, false); //also change this name to what you want.
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
prefsEditor.putBoolean(SWITCH_BOOLEAN, isChecked);
prefsEditor.apply();
}
});
Please refer to SharedPreferences for information on SharedPreferences and this for information on the Switch.
Remember that the Strings supplied for the preference names are case sensitive and need to be the same for it to get the same preference.
来源:https://stackoverflow.com/questions/24910518/how-to-save-the-state-of-an-fragment-in-android