扩展FragmentStateAdapter时各个构造函数有什么区别?

What is the difference between each constructor when extending FragmentStateAdapter?

我正在学习片段,在我制作的应用程序中有一个底部导航栏,第一个有一个带有 ViewPager2 的片段。对于 viewpager2,我创建了一个扩展 FragmentStateAdapter 的自定义适配器,首先我使用了接收 FragmentActivity 的构造函数,然后我使用了接收 FragmentManager 和 Lifecycle 的构造函数。我使用它们的方式是这样的:

CustomAdapter adapter = new CustomAdapter(getActivity());
CustomAdapter adapter = new CustomAdapter(getChildFragmentManager(), getLifeCycle());

两者似乎都工作正常,但我想知道使用一个或另一个之间的区别是什么,以及为什么在第二个适配器上使用 getChildFragmentManager() 而不是 getFragmentManager()。

旁注:需要说明的是,我一次只使用了一个构造函数。

FragmentStateAdapter实际上有三个构造函数:

  • FragmentStateAdapter(FragmentActivity) - 这使用 Activity 的 getSupportFragmentManager() 和 Activity 的 getLifecycle()。如果您的 ViewPager2 直接托管在 Activity
  • 中,这就是您要使用的内容
  • FragmentStateAdapter(Fragment) - 这使用片段的 getChildFragmentManager() 和片段的 getLifecycle()。如果您的 ViewPager2 托管在另一个 Fragment
  • 中,这就是您要使用的
  • FragmentStateAdapter(FragmentManager, Lifecycle) - 这是其他两个构造函数在内部调用的内容。你永远不会使用它,除非你在服务中添加片段,等等,而你根本没有 FragmentActivity

必须始终使用带Fragment的那个(或者如果您想编写更多代码,则使用getChildFragmentManager()+getLifecycle()为了同样的效果)在片段中托管 ViewPager2 时 - 这确保片段的你的 FragmentStateAdapter 正确地在配置更改或进程死亡或重新创建后恢复其状态 - 只有在以下情况下才有可能它们是包含您的 ViewPager2 的片段的子片段。