Introduction to Android Fragments


5th February, 2023

Android Fragment is a reusable Graphical User Component (GUI). In other word, A Fragment is a piece of the Android Activity. Fragments encapsulate views and logic so that it is easier to reuse within activities. In this section we are going to learn an interesting and important topic that is Android Fragments.

What is Android Fragment?

→ Android Fragments cannot exist outside an activity
Fragments can be dynamically added and removed
An Activity can have any number of fragments
Android fragments have their own lifecycle
→ Android resides within the Activities
→ Fragment is a re-usable component
→ A single fragment can be included in multiple activities

Android Activity with a Fragment
Android Activity with two Fragments

Fragments were added in Honeycomb version of Android (Android API 11). You can create fragments by extending Fragment class. We will discuss them later. If our activity has too many functional components, it is difficult to organize the code. Let’s divide the activity into smaller sub-activity. Using Android Fragment makes this task easier.

Types of Android Fragments

  • Single Fragment
    This type of fragment is used to display one single view on the device screen. Mostly used for mobile phones.
  • List Fragment
    List fragment is used to display list-view from which user can select the desired sub-activity. Like menu drawer of the Gmail android application.
  • Fragment Transactions
    This type of fragments supports the transactions from one fragment to another at runtime.

Fragment Manager

Fragment Manager is the main class responsible for performing actions on fragments. such as adding, removing or replacing fragments. You can find a fragment by id (findFragmentById) or tag (findFragmentByTag) using the public method of the Fragment Manager class. In one line, the Fragment Manager takes care of your app’s fragments.

Android Fragment Example

The image below describes the fragments in the Gmail Android app. The list fragment is visible on the left phone screen in the image below. If the user selects any item from the list, the app will take the user to corresponding fragment. Here the user has selected an outbox from the list and a fragment of outbox mail is being displayed on the screen (middle phone screen).


The last phone screen (right side) shows the chat fragment as the chat option is selected from bottom navigation menu.

Happy coding!

Leave a Reply