mckrpk
mckrpk

Reputation: 145

Fragments inside ViewPager are not destroyed

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?

Upvotes: 8

Views: 4287

Answers (1)

cYrixmorten
cYrixmorten

Reputation: 7108

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

Upvotes: 28

Related Questions