4.3 Integrating a Fragment into an Activity

So now we know what a fragment is, how do we go about creating one? Unlike activities, where a new layout XML files must be created for each new Activity made, there are a few options for creating and using a Fragment. Remember, each fragment must be part of an Activity!

One method is to directly insert the fragment into the activity’s XML file using the <fragment> tag, like so:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment android:name="com.example.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>

This is generally bad practice because it ends up being pretty hard to manipulate this fragment when it is hardcoded into the XML like this.

The second method is to programmatically add the fragment to an existing ViewGroup or layout of an activity.

...
    <androidx.fragment.app.FragmentContainerView
    android:id="@+id/fragment_container_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
...

We can then create and launch the fragment through the fragment manager.

val fragmentManager = supportFragmentManager;
fragmentManager.beginTransaction()
    .add(R.id.fragment_container_view, FragmentA())
    .commit()

Fragment Manager

Like the name suggests, a fragment manager manages all the fragments that may exist inside the activity. More importantly, a fragment manager is used for retrieving active fragments by their ids or tags, popping fragments to a back stack when they are paused, and registering a listener to listen for changes on the back stack.

Fragment Transactions

A fragment transaction is an action that is applied to an individual fragment, which includes adding, removing, and replacing a fragment.

Here is a simple example of swapping in a new fragment:

val fragmentManager = supportFragmentManager;
fragmentManager.beginTransaction()
    .replace(R.id.fragment_container_view, FragmentB())
    .commit()

Notice how we are using replace() instead of add() here. If we called add(), we will be adding a new fragment on top of the old fragment, so you would see both at the same time. replace() essentially creates the new fragment and destroys the old ones.

We can also call addToBackStack() before committing the new fragment to save the old fragment in the back stack. This way, when the user clicks the back button on the Android, they will be brought back to the old screen.

Fun fact: Eatery Android doesn’t currently use addToBackStack() in MainActivity so if you click the back button, you will close the app instead of returning to the old fragment!

Last updated