Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 880
mckrpk Avatar asked Oct 24 '14 18:10

mckrpk


1 Answers

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

like image 166
cYrixmorten Avatar answered Sep 28 '22 00:09

cYrixmorten