Getting the current Fragment instance in the viewpager

前端 未结 30 1942
醉话见心
醉话见心 2020-11-22 08:56

Below is my code which has 3 Fragment classes each embedded with each of the 3 tabs on ViewPager. I have a menu option. As shown in the onOpt

30条回答
  •  太阳男子
    2020-11-22 09:21

    You can declare an Array of fragment as register fragments

    class DashboardPagerAdapter(fm: FragmentManager?) : FragmentStatePagerAdapter(fm!!) {
        // CURRENT FRAGMENT
        val registeredFragments = SparseArray()
    
        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val fragment = super.instantiateItem(container, position) as Fragment
            registeredFragments.put(position, fragment)
            return fragment
        }
    
        override fun getItem(position: Int): Fragment {
            return when (position) {
                0 -> HomeFragment.newInstance()
                1 -> ConverterDashboardFragment.newInstance()
                2 -> CartFragment.newInstance()
                3 -> CustomerSupportFragment.newInstance()
                4 -> ProfileFragment.newInstance()
                else -> ProfileFragment.newInstance()
            }
        }
    
        override fun getCount(): Int {
            return 5
        }
    
    }
    

    Then you can use it as

    adapter?.let {
        val cartFragment = it.registeredFragments[2] as CartFragment?
        cartFragment?.myCartApi(true)
    }
    

提交回复
热议问题