Skip to content

Instantly share code, notes, and snippets.

@igoriols
Last active December 30, 2020 15:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igoriols/39a53a0cce000d3c9bd4 to your computer and use it in GitHub Desktop.
Save igoriols/39a53a0cce000d3c9bd4 to your computer and use it in GitHub Desktop.
How to properly retain state of fragments in back stack without using setRetainInstance(true).
/**
* @author Igor Oliveira
*/
public abstract class StatefulFragment extends Fragment {
private Bundle savedState;
private boolean saved;
private static final String _FRAGMENT_STATE = "FRAGMENT_STATE";
@Override
public void onSaveInstanceState(Bundle state) {
if (getView() == null) {
state.putBundle(_FRAGMENT_STATE, savedState);
} else {
Bundle bundle = saved ? savedState : getStateToSave();
state.putBundle(_FRAGMENT_STATE, bundle);
}
saved = false;
super.onSaveInstanceState(state);
}
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
if (state != null) {
savedState = state.getBundle(_FRAGMENT_STATE);
}
}
@Override
public void onDestroyView() {
savedState = getStateToSave();
saved = true;
super.onDestroyView();
}
protected Bundle getSavedState() {
return savedState;
}
protected abstract boolean hasSavedState();
protected abstract Bundle getStateToSave();
}
1. Extend this class;
2. In your Fragment, you must have this:
@Override
protected boolean hasSavedState() {
Bundle sate = getSavedState();
if (sate == null) {
return false;
}
//restore your data here
return true;
}
3. For example, you can call hasSavedState in onActivityCreated:
@Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
if (hasSavedState()) {
return;
}
//your code here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment