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
This is the simplest hack:
fun getCurrentFragment(): Fragment? {
return if (count == 0) null
else instantiateItem(view_pager, view_pager.currentItem) as? Fragment
}
(kotlin code)
Just call instantiateItem(viewPager, viewPager.getCurrentItem()
and cast it to Fragment
. Your item would already be instantiated. To be sure you can add a check for getCount
.
Works with both FragmentPagerAdapter
and FragmentStatePagerAdapter
!