Android中FragmentManager回收片段的目的是什么?

What is the purpose of fragment recycling by FragmentManager in Android?

我知道 Fragment 应该在第一次使用片段时使用 FragmentTransaction 创建并添加到管理器中。但是后来可以通过findFragmentByIdfindFragmentbyTag 等配置更改后找到它

但是在屏幕旋转时,我发现片段的构造函数和所有回调方法onAttachonCreateonCreateViewonStartonResume 被再次调用,即使片段是从 findFragmentByTag 返回的,没有明确调用构造函数。

调用构造函数的事实意味着可以对片段对象进行垃圾回收。那么片段的哪一部分实际存储在配置更改上?如果片段对象被垃圾收集并重新创建,那么回收它的目的是什么?

片段未回收。如果您在屏幕方向后登录 Fragment.toString(),您将获得不同的值,这意味着这些片段实例是不同的,是从头开始创建的。所有生命周期方法都被称为 但是 您可以通过 onSaveInstanceState(Bundle).

保留一些值

对于您调用 setRetainInstance(true) 的片段,情况并非如此。现在唯一重复的生命周期方法是 onCreateViewonViewCreated、(长时间停顿)、onDestroyView。实例相同,字段变量保留

编辑:

Does Android OS automatically destroy and create the fragment and set the same Tag and ID before onCreate is called on the hosting Activity?

TL;DR: 是的。

FragmentState class 字段变量包含有关一个片段的信息,该片段始终 保留(以及其他标签和 ID)。

当你旋转屏幕时 FragmentManagerImpl.restoreAllState(...) 被调用,它要么抓取保留的片段,要么实例化新的片段并将它们重新附加到新的 activity。这是 Activity.onCreate(Bundle).

的一部分

Then what part of the fragment is actually stored on configuration changes?

如上所述的 FragmentState 加上您或框架在 onSaveInstanceState(Bundle) 中写入的任何内容。如果片段被标记为保留,则保存除视图层次结构之外的所有内容。

If the fragment object is garbage-collected and recreated, then what is the purpose of recyling it?

如果它被销毁并从头开始创建(新实例),则根本不会回收。您要么 保留 片段实例 - 同一实例在屏幕方向更改后仍然存在 - 或者保存并恢复实例状态 - 旧片段实例被销毁,新片段实例被创建并填充一些来自旧实例。