How to get a fragment using position from a FragmentStateAdapter with ViewPager2

1.9k Views Asked by At

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?

1

There are 1 best solutions below

0
Zain On BEST ANSWER

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")
    }