I\'m migrating my ViewPager
to ViewPager2
since the latter is supposed to solve all the problems of the former. Unfortunately, when using it with a
The solution to find current Fragment by its tag seems the most suitable for me. I've created these extension functions for that:
fun ViewPager2.findCurrentFragment(fragmentManager: FragmentManager): Fragment? {
return fragmentManager.findFragmentByTag("f$currentItem")
}
fun ViewPager2.findFragmentAtPosition(
fragmentManager: FragmentManager,
position: Int
): Fragment? {
return fragmentManager.findFragmentByTag("f$position")
}
Activity
, use supportFragmentManager
or fragmentManager
.Fragment
, use childFragmentManager
Note that:
findFragmentAtPosition
will work only for Fragments that were initialized in ViewPager2's RecyclerView. Therefore you can get only the positions that are visible + 1.ViewPager2.
from fun ViewPager2.findFragmentAtPosition
, because you don't use anything from ViewPager2 class. I think it should stay there, because this workaround applies solely to ViewPager2.