PSA: v25.1.0 Support Fragments Behavior Change

The most recent Awesome Android Newsletter contained a link to an Android issue about a side-effect of an API change.

Up until a few weeks ago, both for the native implementation of fragments (android.app.Fragment) and the Android Support Library backport in support-v4 (android.support.v4.app.Fragment), when executing a replace() transaction, the fragment being replaced would be called with onStop() before the replacement fragment would be called with onStart().

However, the v25.1.0 version of the backport inverts this by default, with onStart() of the replacement fragment being called before onStop() is called on the fragment being replaced.

And, since this issue is flagged as “working as intended”, this default behavior seems unlikely to change.

Note that the native implementation of fragments behaves as it has – this change has not affected Android 7.1.1, for example. Also note that calling setAllowOptimization(false) on the FragmentTransaction should revert this change and roll you back to the prior behavior.

This is part of a larger optimization change that aims to apply only the subset of your transactions that represent the overall net change in the state of the fragments. Quoting the documentation:

For example, one transaction adds fragment A, a second adds fragment B, then a third removes fragment A. Without optimization, fragment B could expect that while it is being created, fragment A will also exist because fragment A will be removed after fragment B was added. With optimization, fragment B cannot expect fragment A to exist when it has been created because fragment A’s add/remove will be optimized out.

If you have code that is dependent upon the order of these lifecycle events, you will want to double-check how your code behaves with fragment optimizations enabled. If you encounter problems, either adjust your code or disable the optimizations.