A new way to hold fragments in Android

Megha Vaishy
2 min readJun 11, 2022

We all know about Framelayout which is used to host fragments in android.In androidx FragmentContainerView is a new view introduced, a customized layout explicitly designed for Fragments.

Now you guys might be thinking about what was wrong with using Framelayout earlier, observe carefully fragment transactions happening in the below images. Pay attention to the bottom at the time of the fragment transaction, especially the button.

Now as you can see fragment transactions on FragmentContainerView are giving a more clean user experience as compared to Framelayout.

So FragmentContainerView has fixed the fragment transition animation issue, which is the biggest benefit over FragmentLayout. FragmentContainerView starts the exit animation first and then the enter animation to give cleaner look when the transition happens

More about FragmentContainerView:

1.It’s google recommended

2. It extends FrameLayout

3. Adding any other views in FragmentContainerView other than Fragments would throw IllegalStateException. It's not a replacement for Framelayout as it can be used only in the case of inflating fragments.

4. Fragment transactions can be done inside XML directly apart from our conventional way

val fragment = DummyFragment()supportFragmentManager.beginTransaction().add(R.id.container, fragment).commit()

In XML :

The android: name attribute is used to add a default Fragment in the FragmentContainerView container.

<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragment_container"
android:name="com.company.FragmentClass"
android:layout_width="match_parent"
android:layout_height="match_parent" />

under the hood, it uses FragmentTransaction to build and show your fragment, you can do fragment transactions later on to replace it.

5. android: tag can be given optionally inside xml, that can be used to retrieve added fragment using FragmentManager.findFragmentByTag

6. UnsupportedOperationException is thrown by FragmentContainerView if setLayoutTransition method is called or animateLayoutChanges property set to true for API level above17(Jelly Bean). To add any custom animation need to use FragmentTransaction.setCustomAnimations method only.

Happy learning!

--

--