Get current fragment with ViewPager2

后端 未结 11 1974
野的像风
野的像风 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:32

    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")
    }
    
    • If your ViewPager2 host is Activity, use supportFragmentManager or fragmentManager.
    • If your ViewPager2 host is 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.
    • Lint will suggest you to remove 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.

提交回复
热议问题