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
ofFragmentActivity
. But if I callsetContentView
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.