Get current fragment with ViewPager2

2020-05-25 07:55发布

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 FragmentStateAdapter, I don't find any way to get the currently displayed fragment.

viewPager.getCurrentItem() gives the current displayed index and adapter.getItem(index) generally creates a new Fragment for the current index. Unless keeping a reference to all created fragments in getItem(), I have no idea how to access the currently displayed fragment.

With the old ViewPager, one solution was to call adapter.instantiateItem(index) which would return the fragment at the desired index.

Am I missing something with ViewPager2?

7条回答
贪生不怕死
2楼-- · 2020-05-25 08:17

was facing same issue now its solved by adding one object in adapter

class MyViewPager2Adapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {


    private val FRAGMENTS_SIZE = 2

    var currentFragmentWeakReference: WeakReference<Fragment>? = null

    override fun getItemCount(): Int {
        return this.FRAGMENTS_SIZE
    }

    override fun createFragment(position: Int): Fragment {

        when (position) {
            0 -> {
                currentFragmentWeakReference= MyFirstFragment()
                return MyFirstFragment()
            }
            1 -> {
                currentFragmentWeakReference= MySecondFragment()
                return MySecondFragment()
            }
        }

        return MyFirstFragment() /for default view

    }

}

after creating adapter I registered my Viewpager 2 with ViewPager2.OnPageChangeCallback() and overrided its method onPageSelected

now simple did this trick to get current fragment

 private fun getCurrentFragment() :Fragment?{

        val fragment = (binding!!.pager.adapter as MyViewPager2Adapter).currentFragmentWeakReference?.get()

        retrun fragment
    }

I've only tested this with 2 fragments in ViewPager2

cheers guys , hope this mayhelp you.!

查看更多
登录 后发表回答