AppCompat 片段生命周期已更改

AppCompat Fragment lifecycle changed

更新到新的 appcompat 库后 com.android.support:appcompat-v7:25.1.0 在事务中替换片段时我有新的片段生命周期。

例如我有两个片段 FrFirstFrSecond,在 onStartonStop 中有日志,我将第一个替换为第二个,然后将第二个替换为第一个:FrFirst -> FrSecond -> FrFirst.

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

在以前的 appcompat 版本中,我可以阅读此日志:

FrFirst: Navigate to second
FrFirst: stop
FrSecond: start

FrSecond: Navigate to first
FrSecond: stop
FrFirst: start

在 25.1.0 中记录:

FrFirst: Navigate to second
FrSecond: start
FrFirst: stop

FrSecond: Navigate to first
FrFirst: start
FrSecond: stop

所以现在 onStart 之前调用的当前片段 onStop

为什么方法顺序改变了,是支持库中的错误吗?

这是新 appcompat 的预期行为。 如此处所述 https://code.google.com/p/android/issues/detail?id=230415 这是一个

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.

因此,如果您想查看旧行为,可以替换禁用优化的片段:

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