Search code examples
androidandroid-activityfragmentfragmenttransaction

Is it a good idea to perform FragmentTransactions inside a fragment?


As the title suggest, is it a good idea to perform FragmentTransaction inside a fragment?

The way I view this is that, FragmentTransaction requires a containerView id and the Fragment to inflate when calling FragmentTransaction.replace(). The containerView where to get the ID usually resides in the activity layout. So it seems like a good idea to do FragmentTransaction inside the activity rather than in the Fragment.

But I got confused when using SharedElementTransition for fragments. Now it requires a list of Views which will be the sharedElements. These views reside in the Fragment. Now it seems logical to do the FragmentTransaction inside the Fragment itself.

Can anyone guide me on how to compensate for both scenarios?


Solution

  • There's nothing wrong on doing FragmentTransaction inside a fragment as long as it is not redundant, like for example:

    "Container" Fragment
    "Child Fragment" that holds view pager
    View pager has fragments

    Here, you can remove the child fragment and hold the view pager on container fragment instead.

    For FragmentTransaction inside a fragment, you can actually swap the fragment itself by calling getActivity().getSupportFragmentManager(). Here, transaction is happening on Activity not on the fragment. But if you intended to use FragmentTransaction to swap the child of the parent fragment, you can use getChildFragmentManager() on the fragment.

    Also, child fragments is actually supported by android.