Skip to content Skip to sidebar Skip to footer

Fragment Save View State

I have some Fragment with this structure:

Solution 1:

Inside your Fragment class, declare a private variable:

privateboolean condition; // rename to something more descriptive

Now in setIcon() store the value:

this.condition = condition;

Finally save this to the bundle in onSaveInstanceState():

outState.putBoolean("condition", this.condition);

and read it in onActivityCreated():

this.condition = savedInstanceState.getBoolean("condition");
this.setIcon(this.condition);

Note

You don't need to save the text from your TextView. The call to super.onSaveInstanceState() already takes care of this for you.

Solution 2:

You can either save the condition in outState like below:

outState.putBoolean("condition", condition);

and then read it and update the image views

setIcon(savedInstanceState.getBoolean("condition"))

Or You can save the visibility state of the image views by putInt method:

outState.putInt("ic1", control_panel_icon_1.getVisibility());
outState.putInt("ic2", control_panel_icon_2.getVisibility());

and then restore the state:

control_panel_icon_1.setVisibility(savedInstanceState.getInt("ic1"));
control_panel_icon_2.setVisibility(savedInstanceState.getInt("ic2"));

Post a Comment for "Fragment Save View State"