Search code examples
androidandroid-fragmentsandroid-appcompatandroid-lifecyclefragment-lifecycle

AppCompat Fragment lifecycle changed


After updating to new appcompat library com.android.support:appcompat-v7:25.1.0 I've got new fragment lifecycle when replacing fragments in transaction.

E.g. I have two fragments FrFirst and FrSecond with logs in onStart and onStop, and I replace first with second and then second with first: FrFirst -> FrSecond -> FrFirst.

getActivity().getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.content, new FrSecond())
    .commit();

In previous appcompat version I can read this logs:

FrFirst: Navigate to second
FrFirst: stop
FrSecond: start

FrSecond: Navigate to first
FrSecond: stop
FrFirst: start

In 25.1.0 this logs:

FrFirst: Navigate to second
FrSecond: start
FrFirst: stop

FrSecond: Navigate to first
FrFirst: start
FrSecond: stop

So now onStart of presenting fragment called before then onStop of current.

Why method order changed, is it a bug in support library?


Solution

  • This is intended behaviour of new appcompat. As described here https://code.google.com/p/android/issues/detail?id=230415 this is a

    new functionality to optimize the operations and postpone fragment transitions and this is a side effect of that.

    You can disable fragment operation optimizations by calling FragmentTransaction.setAllowOptimization(false). This forces everything to happen in the proper order, but also disallows the operations from optimized.

    So if you want to see old behaviour, you can replace fragments with disabled optimisation:

    getActivity().getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.content, new FrSecond())
        .setAllowOptimization(false)
        .commit();