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?
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:
ViewPager2
is hosted by an activity use supportFragmentManager
: fun getPageFragment(id: Long): Fragment? {
return supportFragmentManager.findFragmentByTag("f$id")
}
childFragmentManager
: fun getPageFragment(id: Long): Fragment? {
return childFragmentManager.findFragmentByTag("f$id")
}