Get current fragment with ViewPager2

In ViewPager2 the FragmentManager by default have assigned tags to fragments like this:

Fragment in 1st position has a tag of "f0"

Fragment in 2nd position has a tag of "f1"

Fragment in 3rd position has a tag of "f2" and so on… so you can get your fragment’s tag and by concatenating the “f” with position of your fragment. To get the current Fragment you can get current position from the viewPager2 position and make your tag like this (For Kotlin):

val myFragment = supportFragmentManager.findFragmentByTag("f" + viewpager.currentItem)

For fragment at a certain position

val myFragment = supportFragmentManager.findFragmentByTag("f" + position)

You can cast the Fragment and always check if it is not null if you are using this technique.

If you host your ViewPager2 in Fragment, use childFragmentManager instead.

REMEMBER

If you have overriden the getItemId(position: Int) in your adapter. Then your case is different. It should be:

val myFragment = supportFragmentManager.findFragmentByTag("f" + your_id_at_that_position)

OR SIMPLY:

val myFragment = supportFragmentManager.findFragmentByTag("f" + adapter.getItemId(position))

If you host your ViewPager2 in Fragment, use childFragmentManager instead of supportFragmentManager.

Leave a Comment