Get current fragment with ViewPager2

后端 未结 11 1973
野的像风
野的像风 2020-12-24 01:15

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

11条回答
  •  粉色の甜心
    2020-12-24 01:40

    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.

提交回复
热议问题