FragmentContainerView
Learn how to add fragments into FragmentContainerView
History
Usually in Android, before NavGraph if we want to add a fragment dynamically we used to add container layout mostly FrameLayout in the XML and then add the required instance to the container using fragment manager. We used to use different kinds of layouts before but none of these layouts are optimized for fragment transactions or fragments stuff. As the fragments usage has become a common thing in every app to simplify that and to optimize the fragments stuff Android team came up with FragmentContainerView. In this post let’s check out what is FragmentContainerView and how to use it.
What is FragmentContainerView?
FragmentContainerView is basically a custom view designed extending FrameLayout. In simple terms, we can say FragmentContainerView is a custom layout designed specifically for dealing with fragments. As it was extending FramLayout it can reliably handle Fragment Transactions and has some more additional features related to fragment behavior. Unlike other ViewGroups, it only handles attributes related to fragments. So we should not use FragmentContainerView as a replacement for other ViewGroups (FrameLayout, LinearLayout, etc) outside of Fragment use cases.
Attempting to add any other view other than fragments will result in an IllegalStateException.
Pre-requisites
FragmentContainerView first came to limelight in Android Dev Summit 2019. Add the following dependencies to build.gradle file.
implementation "androidx.fragment:fragment-ktx:1.2.0-rc01"How to add a Fragment to FragmentContainerView
Adding Fragment to FragmentContainerView has a similar procedure of adding a fragment to FrameLayout.






