First define a SparseArray in your ViewPagers’ adapters like below. In this array we’ll hold the instance of fragments.
SparseArray<Fragment> registeredFragments = new SparseArray<>();
And Override your Adapters’ instantiateItem method.
@Override public Object instantiateItem(ViewGroup container, int position) { Fragment fragment = (Fragment) super.instantiateItem(container, position); registeredFragments.put(position, fragment); return fragment; }
Also Override destroyItem method of your ViewPagers
@Override public void destroyItem(ViewGroup container, int position, Object object) { registeredFragments.remove(position); super.destroyItem(container, position, object); } And define a new method to get your ViewPager Fragments instance. public Fragment getRegisteredFragment(int position) { return registeredFragments.get(position); }
And finally set add a PageChangeListener to your ViewPagers:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // Here's your instance YourFragment fragment =(YourFragment)yourPagerAdapter.getRegisteredFragment(position); } @Override public void onPageScrollStateChanged(int state) { } });
Or
int position = viewPager.getCurrentItem(); YourFragment fragment =(YourFragment)yourPagerAdapter.getRegisteredFragment(position);
References
https://stackoverflow.com/questions/39143087/how-to-get-the-current-fragment-displayed-in-a-specific-tab-of-a-viewpager
https://stackoverflow.com/questions/8258759/getting-the-current-position-of-a-viewpager