Android - 在删除最后一个片段之前将片段添加到容器中

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

我有一个关于 FragmentTransaction 的问题。所以我依靠每个 Fragment 中的 onDestroyView()onStop() 来显示或隐藏 activity 底部的工具栏。这是我进行交易的方式:

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

当我调试时,它显示新的 Fragment 在被替换的 Fragment 经历 onDestroyView()onStop() 之前经历了它的 onCreateView()

这是最近发生的事情,我发现工具栏显示异常,直到今天早上才有机会查看。有什么提示吗??

不久前在支持库中更改了此行为,请参阅 https://code.google.com/p/android/issues/detail?id=230415

您可以切换到该帖子中所述的旧行为:

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.

另一种方法是不依赖 onDestroyView()onStop() 被调用,而是处理新片段 onCreateView() 中已经存在的工具栏。例如,始终替换 onCreateView() 中的工具栏,并且仅在 onStop() / onDestroy() 中删除工具栏(如果工具栏仍然是由自己的片段创建的)。