1

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?

Zach
  • 3,909
  • 6
  • 25
  • 50
  • 1
    I found that I can get the method to be called again when using a view pager with 100 fragments, scrolling to position 10 or so, and then doing a garbage collection via Android Studio profiler, but it doesn't act bad/break/crash/etc. when re-using a fragment from the passed in fragmentlist - the value there is still valid/alive, so I'm still not sure what is best practice here. – Zach Apr 05 '21 at 18:44

0 Answers0