Search code examples
androidkotlinandroid-viewpagerandroid-viewpager2fragmentstateadapter

ViewPager2, FragmentStateAdapter, and conflict between pager's currentItem and adapter's createFragment's position parameter


When implementing ViewPager2 and its associated FragmentStateAdapter for its contents in Kotlin, I ran into a weird issue: It has to do with the adapter's createFragment(position: Int) method and viewPager2's setCurrentItem(item: Int, smoothScroll: Boolean). Currently, implementing this for an adapter of size 2 items is fine, being able to start from position 0 of the view pager and able to change items as intended.

The issue then comes from attempting to set the viewPager's currentItem value at the adapter's creation to be a non-zero index value to change the default starting page to the 2nd page(index 1). The createFragment's method from the adapter and its position parameter does not match with the index I set with the viewPager's setCurrentItem method.

Below is sample code to demonstrate(please excuse usage of view binding):

 binding.myViewPager2.apply {
     adapter = MyFragmentStateAdapter(it, this@MyFragment)
     currentItem = 1 //start on 2nd page instead of 1st on viewpager2's load
 }

 //Here is my FragmentStateAdapter code
 class MyFragmentStateAdapter(private val model: Model, fragment : Fragment) : FragmentStateAdapter(fragment) {
      override fun getItemCount(): Int {
          return model.listItems.size
      }

      override fun createFragment(position: Int): Fragment {
         val item : dataSourceModel = model.listItems[position] 
         Log.d("LogNameHere", "position: $position") //If CurrentItem is set to 1, this is still 0.
         return MyFragment.createInstance(position, dataSourceModel.dataA)
}

The above code executes properly until I notice that currentItem does not equal to the position paramater used in createFragment method; currentItem is set to 1, viewPager loads the 2nd page properly, but the position parameter in createFragment is set to 0.

I'm confused and lost as I need the position to be accurate to display proper data in MyFragment. I need the 2nd page to not show the 1st page's data and createFragment's position parameter being the same as the current page is key to that.

I'll be happy to provide more explanation and code if needed to explain my predicament.

How can I have it so that I can start the ViewPager on the second page with the proper data based on the index provided to it? Thank you.


Solution

  • Marking this question as answered through another question asked on SO.

    ViewPager2 selectCurrentItem - select Tab, but place wrong Fragment inside this tab