Search code examples
androidandroid-fragmentsfragmenttransaction

Android - Fragment is added to container before the last Fragment is removed


I have a problem regarding FragmentTransaction. So I rely on onDestroyView() and onStop() in every Fragment to show or hide a toolbar in the bottom of activity. Here's how I do the transaction :

getSupportFragmentManager().beginTransaction()
    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
    .replace(R.id.activity_frame, fragment, tag)
    .addToBackStack(tag)
    .commit();

When I debug, it shows that the new Fragment goes through its onCreateView() before the replaced Fragment goes through onDestroyView() and onStop().

This just happened recently, I realized that the toolbar was showing abnormal behavior and haven't had the chance to check it out till this morning. Any hint on this??


Solution

  • This behaviour was changed in the support library a while ago, see https://code.google.com/p/android/issues/detail?id=230415

    You can switch to the old behaviour like described in that thread:

    This is an intended behavior change. There is 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.

    Another approach would be to not rely on onDestroyView() and onStop() beeing called, but rather handling the already present toolbar in onCreateView() of the new Fragment. For example by always replacing the toolbar in onCreateView() and only removing the toolbar in onStop() / onDestroy() if the toolbar is still the one created by the own fragment.