android - AppCompat fragment 生命周期已更改

标签 android android-fragments android-appcompat android-lifecycle fragment-lifecycle

更新到新的 appcompat 库 com.android.support:appcompat-v7:25.1.0 后,我在事务中替换 fragment 时获得了新的 fragment 生命周期。

例如我有两个 fragment FrFirstFrSecond,在 onStartonStop 中有日志,我将 first 替换为 second 然后第二与第一: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

所以现在在 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/

相关文章:

android - 检测 Android 是否在车内

Android 支持库 27、Fragment 更新?

android - 场景与 fragment 和 View

android - AppCompat 工具栏深色主题样式不适用于 21 之前的设备

Android Color Drawable 资源

android - 在 Android 库项目中包含 AAR 依赖项

android - 自定义 Android appcompat Actionbar : how to remove bottom border on v11+ devices

android Material 设计与 AppCompatActivity

设置 ActionBar 颜色时的 Android UI 故障

java - 文本在 fragment 内更改后,Android 调用一次函数