What is difference between getSupportFragmentManager() and getChildFragmentManager()?

Solution 1:

The definition of getChildFragmentManager() is:

Return a private FragmentManager for placing and managing Fragments inside of this Fragment.

Meanwhile the definition of getFragmentManager() (or in this case getSupportFragmentManager()) is:

Return the FragmentManager for interacting with fragments associated with this fragment's activity.

Basically, the difference is that Fragment's now have their own internal FragmentManager that can handle Fragments. The child FragmentManager is the one that handles Fragments contained within only the Fragment that it was added to. The other FragmentManager is contained within the entire Activity.

In this case, what I'm guessing is you've added the Fragments to the Activity's FragmentManager. You get the child FragmentManager which doesn't contain what you are looking for. Thus you get the exception because it can't find the Fragment with the given ID because it's in a different FragmentManager.

Solution 2:

getFragmentManager belong to Activity
getChildFragmentManager belong to Fragment

Example we have a app which have MainActivity, Fragment1, Fragment2, container_view_on_main is a layout in activty_main.xml

TO display Fragment1 on MainActivity we must use getSupportFragmentManager()

getSupportFragmentManager().beginTransaction().replace(R.id.container_view_on_main, Fragment1.newInstance());

TO display Fragment2 from Fragment1 we have 2 way

USE getFragmentManager()

getFragmentManager().beginTransaction().replace(R.id.container_view_on_main, Fragment1.newInstance());

USE getChildFragmentManager()

First, we have to create a layout with id container_view_on_fragment1 inside fragment1.xml, then

getChildFragmentManager().beginTransaction().replace(R.id.container_view_on_fragment1, Fragment2.newInstance()).commit();

CONCLUSION

In this demo, I think we should use getFragmentManager() when go from Fragment1 to Fragment2 because it is simple and good for performance (Fragment1 will stop when Fragment2 open)

When we use getChildFragmentManager()?
Example your MainActivity have a ViewPager which have 3 pages, inside each pages you need to replace some fragment.

MORE
- getParentFragment()
getFragmentManager() => return null
getChildFragmentManager() => always return root fragment (Fragment1 in demo even we go to Fragment3,,... )

This answer is base on my understand so please correct me if I am wrong. Hope it help