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: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s