Problem with restoring fragments from the backstack ?
Recently, I have lost a bit of time on restoration problems with fragments returning from the backstack. I realized that I wasn’t that familiar with the fragment lifecycle when the backstack is involved and its implications.
Fragment lifecycle and backstack :
You have to see that, when the fragment is in the backstack, he still “lives”. So, it is saved (its state), destroyed, recreated then restored when the activity is destroyed and recreated.
When it is restored from the backstack, only its view is recreated (and more, as the fragment is not necessarily destroyed, the view can still be present).
2 consequences :
- when the fragment is restored from the backstack, if the activity has not been recreated since, the view still exists and is reusable so no need to replay the onCreateView().
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment or reuse the existing one
View view = getView() != null ? getView() :
inflater.inflate(R.layout.fragment_fragment2, container, false);
return view;
}
The onViewCreated() can also be executed uselessly depending of how you use it. Be careful as well with the refresh of the action bar.
- if you make state restorations in the onCreateView() or in the onViewCreated(), its will be lost in case of a double orientation change when the fragment is in the backstack. Actually, after the first change, the state will be saved then lost because only the onCreate() will pass. The second orientation change will then triggers the onSaveInstanceState() on a null state.
=> if your fragment is backstack-able, make your state restorations in the onCreate()
Link to a github project to test the fragment lifecycle when the backstack is involved
Android Developer at jacquesgiraudel.com