Android Basics – Learn about Nested Fragments

A Fragment can contain child Fragments just like an Activity can contain Fragments. For this you need to add the nested fragment programatically.

For example in the Employee App, that you have created, in the detail view you can add a nested fragment. To do this you need to add a FrameLayout attribute to the Layout XML file.

Here is the updated fragment_employee_detail.xml

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”>

<!– TODO: Update blank fragment layout –>
<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/employeeDetailNameId”
android:layout_margin=”10dp”
android:gravity=”center”
android:text=”Ankur”/>

<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/employeeDetailTitleId”
android:layout_margin=”10dp”
android:gravity=”center”
android:text=”Developer”/>

<!– Child Fragment –>
<FrameLayout
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/employeeAddressFragmentId”
/>

</LinearLayout>

In the Java Code we will have to replace this FrameLayout with the desired fragment using the getChildFragmentManager(). Instead of the getFragmentManager() which we used in the Activity. This is needed to manage back button clicks in Fragments.

Watch the video to learn more. Source code available here.

//Handle the Child Fragment.
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
EmployeeListFragment elf = new EmployeeListFragment();
ft.replace(R.id.employeeAddressFragmentId, elf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
//End