I have been learning how to use FragmentStateAdapter and ViewPager2, and one of the issues I'm encountering is the logic behind what to do in createFragment
. I know a fragment must be returned, but some sample apps have a list of fragments passed to the adapter and do something like:
override fun createFragment(position: Int): Fragment {
fragmentList[postion]
}
While other samples create the fragments in the method like:
override fun createFragment(position: Int): Fragment {
when (position) {
0 -> return FragmentOne()
1 -> return FragmentTwo()
2 -> return FragmentThree()
}
// ...
}
I feel that the second option is safer and I wanted to prove that it would be bad to do the first approach, but I've been unable to see any bad behavior/issues when using the first option. I've gone to the extreme and setup a view pager to use 100 fragments and an offscreenPageLimit
value set to 1, for example! In these cases, fragment views are being re-created more often, but createFragment
is never called when viewing older fragments that have been swiped past before.
Am I missing something simple here? When do fragments need to be re-created?