Home » Android » android – Fragments inside ViewPager are not destroyed

android – Fragments inside ViewPager are not destroyed

Posted by: admin June 15, 2020 Leave a comment

Questions:

In my MainActivity in onCreate method I add() MainFragment to FrameLayout main_view_container:

        if (savedInstanceState == null) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.main_view_container, new MainFragment(), MainFragment.FRAGMENT_TAG);
        fragmentTransaction.commit();
    }

In my MainFragment I have ViewPager with FragmentStatePagerAdapter and every page is Fragment itself (PagerFragment).

Then at some point after button click I want to replace whole MainFragment with another Fragment (ReplacementFragment) and add transaction to back stack so I can go back to MainFragment on back button pressed. So I do the following:

FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.main_view_container, new ReplacementFragment(), null);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();

After I commit transaction MainFragment is stopped and onDestroyView() is called but completely nothing happens with PagerFragments (that are in ViewPager in MainFragment) Not event a single onStop() call. Then when I go back MainFragment’s View is recreated in onCreateView() which means new Instance of ViewPager as well, but still nothing with PagerFragments.

How is that possible that in parent Fragment onDestroyView is called but not in children Fragments?

How to&Answers:

You must use getChildFragmentManager() when creating pager adapter inside MainFragment.