

Let’s look at some commonly faced issues. If ViewPager is going to have less than three fragments, use FragmentPagerAdapter. So when you are going to have many fragments, use FragmentStateAdapter. FragmentStatePagerAdapter only stores the savedInstanceState of fragments and destroys all the fragments when they lose focus. So never try to use getSupportFragmentManager in a fragmentįragments When Using ViewPager and When to Use FragmentStateAdapter vs FragmentPagerAdapterįragmentPagerAdapter stores the whole fragment in memory and can cause an increase of memory overhead if a large number of fragments are used in ViewPager. It will not just leak parent fragment but also all of the child fragments since none of them can be cleared from heap memory. Now if close your Parent fragment, it will be closed but it will not be destroyed because all child fragments are active and they are still in memory, hence causing leak. But why does it happen? Well, you have a stack of fragments which are used by ViewPager, and all these fragments stack in activity since you used getSupportFragmentManager.

The most important issue caused by using getSupportFragmentManager in fragments is a memory leak. When it comes to common mistakes people make when they are using ViewPager inside a Fragment, they often pass getSupportFragmentManager, which is a fragment manager for an activity, and it causes issues such as memory leaks or ViewPager not updating properly. Here is the official link for this for better understanding.

Whenever you are ViewPager inside a fragment you will use getChildFragmentManager.Įxample: FragmentManager cfManager=getChildFragmentManager() viewPagerAdapter = new ViewPagerAdapter(cfManager)

getSupportFragmentManager is associated with an activity.GetSupportFragmentManager and getChildFragmentManagerįragmentManager is class provided by the framework which is used to create transactions for adding, removing or replacing fragments.
