6.1 What are Fragments?

Say you have a complex activity that receives many different forms of user input and displays many different things to the user, like Facebook’s home screen. For these screens, fragments are used to divide up the activity into parts that are easier to work with.

Fragments are similar to activities in that each fragment has its own lifecycle methods (ie. onCreate(), onResume()) and has a unique layout file associated with it. However, unlike Activities, fragments don’t need to be declared in AndroidManifest.xml; instead, they must be attached to a larger activity.

Fragments are also often used to quickly change subsections of the screen while keeping other parts intact. For example, in Eatery, we have one main activity with three fragments (one for each tab).

Although it may seem like we are completely transitioning screens, there is only one activity (MainActivity.kt) that was used in creation of these displays. You’ll notice that the toolbar and the bottom navigation bar does not change as you switch tabs. This is because the toolbar and bottom navigation bar are created in MainActivity.kt.

Inside the main activity, we added a layout for displaying the different fragments, which exists between the toolbar and the bottom navigation bar. When the user switches the tab, the corresponding fragment is swapped in.

Last updated