Skip to content Skip to sidebar Skip to footer

How To Save The State Of An Fragment In Android?

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:

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 :)

Solution 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)

SwitchmySwitch= (Switch) findViewById(R.id.mySwitch); // or however else you want to initialize itfinalStringSWITCH_BOOLEAN="switchBoolean";
finalStringPREFERENCE_NAME="sharedPreferenceFile";
finalSharedPreferencesprefs= getActivity().getSharedPreferences(PREFERENCE_NAME, 0); // change the name to what you want, this is an xml file that stores your preferencesfinal SharedPreferences.EditorprefsEditor= prefs.getEditor();

mySwitch.setChecked(prefs.getBoolean(SWITCH_BOOLEAN, false); //also change this name to what you want.

mySwitch.setOnCheckedChangeListener(newOnCheckedChangeListener(){
    @OverridepublicvoidonCheckedChanged(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.

Post a Comment for "How To Save The State Of An Fragment In Android?"