I have been told to use the createFragment override of the FragmentStateAdapter to get the current fragment by index.
This is how my adapter appears to be .
class AddRestaurantPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
FragmentStateAdapter(fragmentManager, lifecycle) {
private var fragments = listOf<Fragment>(
FragmentA.newInstance(),
FragmentB.newInstance(),
FragmentC.newInstance(),
FragmentD.newInstance()
)
override fun getItemCount() = 4
override fun createFragment(position: Int) =
fragments[position]
}
This works fine until we force an onSaveInstance/OnRestoreInstance on this activity/fragment.
The ViewPager2 reloads the already existing fragments on it , and we need a way to access that. This is evidenced by the following LOC in the FragmentStateAdapter class
private void ensureFragment(int position) {
long itemId = getItemId(position);
if (!mFragments.containsKey(itemId)) {
// TODO(133419201): check if a Fragment provided here is a new Fragment
Fragment newFragment = createFragment(position);
newFragment.setInitialSavedState(mSavedStates.get(itemId));
mFragments.put(itemId, newFragment);
}
}
After activity/fragment recreation , you'd find that the this If block never executes because mFragments would already contain the fragment added before the activity was collected.
So I was wondering how should be extract the fragments already in the viewpager2