3

I'm learning about fragments, and in the app that I'm making I have a bottom navigation bar, and the first one has a fragment with a ViewPager2. For the viewpager2 I created a custom adapter that extends FragmentStateAdapter, first I used the constructor that receives a FragmentActivity, and the I used the constructor that receives a FragmentManager and a Lifecycle. The way I used them was like this:

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

Both seemed to work fine, but I'm wondering what is the difference between using one or the other and why it is getChildFragmentManager() and not getFragmentManager(), on the second adapter.

Side note: Just to be clear I only used one of the cosntructors at a time.

Rodrigo Pina
  • 81
  • 1
  • 8

1 Answers1

8

There's actually three constructors for FragmentStateAdapter:

  • FragmentStateAdapter(FragmentActivity) - this uses the Activity's getSupportFragmentManager() and the Activity's getLifecycle(). This is what you'd use if your ViewPager2 was directly hosted within an Activity
  • FragmentStateAdapter(Fragment) - this uses the Fragment's getChildFragmentManager() and the Fragment's getLifecycle(). This is what you'd use if your ViewPager2 was hosted within another Fragment
  • FragmentStateAdapter(FragmentManager, Lifecycle) - this is what the other two constructors call internally. You wouldn't ever use this unless you were adding fragments to a service, etc. where you don't have a FragmentActivity at all.

You must always use the one that takes a Fragment (or use getChildFragmentManager()+getLifecycle() if you want to write more code for the same effect) when hosting a ViewPager2 within a Fragment - this ensures that the Fragment's your FragmentStateAdapter creates correctly have their state restored after a configuration change or process death or recreation - something that is only possible when they are child fragments of the fragment that has your ViewPager2 within it.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443