Home » Android » Android ViewPager not calling onDetach/onDestroy/onDestroyView for when being replaced in a container

Android ViewPager not calling onDetach/onDestroy/onDestroyView for when being replaced in a container

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a FrameLayout container in which I use the replace method to put a fragment when an item is selected from the navigation drawer.

getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, fragment.getFragmentTag()).commit();

I have a fragment which has a ViewPager within it. I have 3 fragments which are displayed in a tab layout with the ViewPager. When I select another item from the navigation drawer the fragment with the ViewPager is replaced but the fragments within are not detached. The system calls only the fragment with the ViewPager onDetach/onDestroy etc. methods but not the methods of the fragments it contains.

I am using FragmentPagerAdapter and I tried with the FragmentStatePager adapter. Nothing changes. I am using the default setOffscreenPageLimit(1);

How can I get my ViewPager fragments methods onDetach/onDestroy called?

Thanks!

How to&Answers:

Are you using the FragmentManager or the child Fragment Manager? If you create a Fragment inside another Fragment and you want the inner Fragment to behave like the outer, you should get the child fragment manager from the outer fragment and use it to create the inner fragments. See this.