7

I have a nested Fragment that I am trying to restore the state given an orientation change.

So firstly my setup is as follows:

Activity -> ParentFragment (SetRetainInstance(true)) -> ChildFragment

In My Child fragment I have the onSaveInstance code as follows:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // Serialize the current dropdown position.
    outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActivity().getActionBar()
            .getSelectedNavigationIndex());
}

However when I orientate the device in all the LifeCycle events return a savedInstance state of null.

Am I doing this incorrectly for a ChildFragment? Why is my state not getting saved and returned?

jww
  • 97,681
  • 90
  • 411
  • 885
Donal Rafferty
  • 19,707
  • 39
  • 114
  • 191

1 Answers1

7

It's due to setRetainInstance(true) of your parent fragment. Android retains a fragment with all its children fragments. So your ChildFragment is not destroyed, and that's why you get null in savedInstanceState. The documentation of onCreateView states:

savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given here.

You can try to comment setRetainInstance(true) out and ensure you get correct value for savedInstanceState.

Ayzen
  • 933
  • 7
  • 10