I'm reading Programming for Android and in the book it says:
It is entirely possible that an activitys onCreate will be called while it is still associated with a previously created fragment. Simply adding a new fragment whenever onCreate method is called will leak fragments. To prevent that, the example code makes use of the fragment managers tagging and location features.
The code is:
super.onCreate( state);
setContentView( R.layout.main);
FragmentManager fragMgr = getFragmentManager();
FragmentTransaction xact = fragMgr.beginTransaction();
if (null = = fragMgr.findFragmentByTag( FRAG1_TAG)) {
xact.add( R.id.date_time, new DateTime(), FRAG1_TAG);
}
xact.commit();
Can someone explain why this is needed in onCreate?
I thought that a fragments lifecycle was always dependent on the activity's lifecycle, and onCreate in an activity is always called when the activity is created (i.e it is always dead).
So if a fragments lifecycle is tied to the activity, shouldn't all the fragment die when an activity dies and therefore the fragments will always be null when onCreate is called in an Activity?
Are there exceptions or can someone explain why my thinking is not correct (I actually think it is not correct but have no idea why?)
The fragments will get destroyed with the Activity
but the FragmentManager
will remember them unless you're completely finishing the Activity
. If the Activity
is killed due to a configuration change and then it gets recreated the FragmentManager
needs to restore any previously committed fragments. That is why you check to see if the Fragment
isn't already in the FragmentManager
. If it's there then abort the transaction otherwise will end up with two fragments(the new one that you just created and the old one that the FragmentManager
remembered and it will restore).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With