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

Author: Ankur

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

One thought on “Android Basics – Learn about Nested Fragments”

  1. See..I made a Relativelayout in fragment(A)….I have to show one fragment at a time (two nested fragment(B,C))on that….By default i called fragment B through A…But when I am calling to replace fragment C through B it is giving error that “view not found for RelativeLayout id”…..Where i am missing????

    Like

Leave a comment