0

I am using ViewPager2 with FragmentStateAdapter to create a collection of fragments. I want to access a particular fragment on the basis of its position in the Adapter. How can I achieve the same?

Zain
  • 37,492
  • 7
  • 60
  • 84
thebadassdev
  • 156
  • 9

1 Answers1

3

You can get fragments by Ids using Fragment manager's findFragmentByTag("f$id")

But to do that you need to override getItemId() in the FragmentStateAdapter to return the position, so that the id now equals to the position.

override fun getItemId(position: Int): Long {
    return position.toLong()
}

Then to get a fragment at a position:

  • If the ViewPager2 is hosted by an activity use supportFragmentManager:
    fun getPageFragment(id: Long): Fragment? {
        return supportFragmentManager.findFragmentByTag("f$id")
    }
  • And if it's hosted by a fragment use childFragmentManager:
    fun getPageFragment(id: Long): Fragment? {
        return childFragmentManager.findFragmentByTag("f$id")
    }
Zain
  • 37,492
  • 7
  • 60
  • 84