The long and short of it: if you are using any subclass of
FragmentActivity (like the new
AppCompatActivity) and you are thinking of doing any kind of fragment transaction in
onResume, do it in
If you feel like some detail and some caveats, read on. If not, no worries. Have a good one and see you next post.
Still here? Okay.
What is the difference between
onResumeFragments? From the documentation for
Dispatch onResume() to fragments. Note that for better inter-operation with older versions of the platform, at the point of this call the fragments attached to the activity are not resumed. This means that in some cases the previous state may still be saved, not allowing fragment transactions that modify the state. To correctly interact with fragments in their proper state, you should instead override onResumeFragments().
Basically, you cannot be sure that an activity's existing fragments have resumed in the activity's
onResume and should avoid fragment transactions until
onResumeFragments, when their state has restored and they have actually resumed.
By doing this you can avoid ye good ol'
IllegalStateException which Android throws whenever you try to perform transactions on a fragment after its state has already been saved (via
onSaveInstanceState). If the fragment's activity is destroyed and re-created, you will lose those post-save changes. For a better and fuller explanation of this, read Alex Lockwood's "Fragment Transactions & Activity State Loss".
Admittedly, I learned about
onResumeFragments long after I learned about fragments and fragment transactions. Most basic material on activity lifecycle omits it since it only exists in
FragmentActivity in the support library and not in the SDK
Activity class. However,
onResumeFragments is a good-to-know.
Now after saying all that, my $0.02 these days is just to avoid doing fragment transactions in lifecycle events as much as possible and particularly in
onResume/onResumeFragments and that considering doing so is usually a hint that either your UI/UX or business logic needs some review.
But that's a rant for another day.