20

When using FragmentActivity it automatically restores fragment state and recreates all fragments.

I know this is done mainly saving the state in onSaveInstanceState and then restored in activity's onCreate. Looking a little on the code I've seen that all fragments are recreated (or only attached if retainInstance is true) and added to the FragmentManager but it's not clear to me in which way they are added to the view, because view isn't automatically restored.

My original problems were that I get duplicates of some fragments similar to that other question. I workarrounded that in onCreate with:

   Fragment f = fm.findFragmentByTag(tagName);
   if(f==null) {
       f = createFragment();
       fm.beginTransaction().add(R.id.myContainer,f,tagName).commit();
   }  else {
     //Nothing it's on the view
   }

Now it works, but I still doesn't understand completely how it works.

My doubts are:

  • In which moment and how are fragments attached to the View? I've experimented that fragment restoration is done in onCreate of FragmentActivity. But if I call setContentView after that, how the fragment attach to the view?
  • Can I prevent fragment recreation without overwriting onSaveInstanceState? Because due to different orientation layouts with different number of fragments my original intention was to recreate only one state fragment marked as retained an don't restore the other view fragments that are not marked as retained.
Community
  • 1
  • 1
lujop
  • 13,504
  • 9
  • 62
  • 95

1 Answers1

8

View hierarchy in not restored automatically. So, in Fragment.onCreateView() or Activity.onCreate(), you have to restore all views (from xml or programmatically). Each ViewGroup that contains a fragment, must have the same ID as when you created it the first time. Once the view hierarchy is created, Android restores all fragments and put theirs views in the right ViewGroup thanks to the ID. Let say that Android remembers the ID of the ViewGroup on which a fragment was. This happens somewhere between onCreateView() and onStart().

I think it could be possible to keep fragment recreation but, on the ViewGroup that hold the fragment, set visibility to GONE. In this way, the fragment doesn't appear and you can remove it programmatically later.

Gabriele Mondada
  • 497
  • 4
  • 14