更新到新的 appcompat 库 com.android.support:appcompat-v7:25.1.0
后,我在事务中替换 fragment 时获得了新的 fragment 生命周期。
例如我有两个 fragment FrFirst
和 FrSecond
,在 onStart
和 onStop
中有日志,我将 first 替换为 second 然后第二与第一:FrFirst -> FrSecond -> FrFirst
。
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, new FrSecond())
.commit();
在以前的 appcompat 版本中,我可以阅读此日志:
FrFirst: Navigate to second
FrFirst: stop
FrSecond: startFrSecond: Navigate to first
FrSecond: stop
FrFirst: start
在 25.1.0 中这个日志:
FrFirst: Navigate to second
FrSecond: start
FrFirst: stopFrSecond: Navigate to first
FrFirst: start
FrSecond: stop
所以现在在 onStop
之前调用呈现 fragment 的 onStart
。
为什么方法顺序变了,是支持库的bug吗?
最佳答案
这是新 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.
所以如果你想看到旧的行为,你可以用禁用的优化替换 fragment :
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, new FrSecond())
.setAllowOptimization(false)
.commit();
关于android - AppCompat fragment 生命周期已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41236010/