Android Fragment Example Tutorial

Android Fragment Example Tutorial

This tutorial will cover Android Fragment Example in application development. A Fragment stands for a behavior or a section of user interface in an Activity. You can combine several fragments in one activity to produce a multi-pane UI and reuse a fragment in a lot of activities.

You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or take away while the activity is running like a “sub activity” that you can reuse in a lot of activities.

A fragment should at all times be embedded in an activity and the fragment’s lifecycle is straightforwardly affected by the host activity’s lifecycle.

For example, when the activity is paused, all fragments in it are as well paused, and when the activity is damaged, all fragments in it are as well destroyed.

However, while an activity is running, it is in the resumed lifecycle state, you can pressure every one of the fragments discretely, like add or remove them.

When you carry out a fragment transaction like that, you can also add it to a back stack that’s managed by the activity—each back stack entry in the activity is a record of the fragment transaction that took place.

The back stack allows the user to reverse a fragment transaction (move backwards), by hitting the Back button.

When you add a fragment as a section of your activity layout, it lives in a ViewGroup inside the activity’s view hierarchy and the fragment defines its own view layout.

You can put in a section into your activity layout by declaring the fragment in the activity’s layout file, as a <fragment> element, or from your application code by adding it to an already existing ViewGroup.

Even so, a fragment is not required to be a part of the activity layout; you may also make use of a fragment without its own UI as an invisible worker for the activity.

This article explains how to create your application to use fragments, including how fragments can conserve their state when added to the activity’s back stack, share events with the activity and other fragments in the activity, take part in the activity’s action bar, and a lot more.

Design Philosophy

Android initiated fragments in Android 3.0 (API level 11), principally to support more dynamic and flexible UI designs on large screens, like tablets. Due to the fact that a tablet’s screen is much larger than that of a handset, there’s more room to combine and exchange UI components.

Fragments permit such designs without the requirement for you to manage complex changes to the view pecking order. By separating the layout of an activity into fragments, you become capable of changing the activity’s appearance at runtime and conserve those changes in a back stack that’s managed by the activity.

For instance, a news application can make use of one fragment to illustrate a list of articles on the left and another fragment to display an article on the right—both fragments emerge in one activity, side by side, and each fragment possess its own set of lifecycle callback procedures and takes care of their own user input events.

Therefore, rather than making use of  one activity to choose an article and another activity to read the article, the user can choose an article and read it all within the same activity.

You ought to design each fragment as a modular and reusable activity element. That is, due to the fact that every one of the fragments defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in a lot of activities, so you ought to design for reuse and steer away from directly influencing one fragment from another fragment.

This is particularly important due to the fact that a modular fragment permits you to alter your fragment combinations for various screen sizes. When designing your application to sustain both tablets and handsets, you can reuse your fragments in various layout configurations to optimize the user experience based on the accessible screen space.

For instance, on a handset, it might be essential to alienate fragments to make available a single-pane UI when more than one cannot fit within the same activity.

For instance—to go on with the news application example—the application can embed two fragments inActivity A, when running on a tablet-sized device. Nevertheless, on a handset-sized screen, there’s not enough room for both fragments, therefore Activity A includes only the fragment for the list of articles, and when the user chooses an article, it begins Activity B, which comprises the second fragment to read the article. Thus, the application supports both tablets and handsets by reusing fragments in diverse arrangements.

To produce a fragment, you ought to create a subclass of Fragment (or an on hand subclass of it). The Fragment class has code that looks a lot like an Activity. It is made up of callback methods akin to an activity, like onCreate(), onStart(), onPause(), and onStop(). In fact, if you’re changing an existing Android application to use fragments, you may merely move code from your activity’s callback methods into the respective callback methods of your fragment.

Typically, you ought to implement at least the following lifecycle methods:

onCreate ()

The system calls this when producing the fragment. Within your implementation, you ought to start necessary components of the fragment that you want to preserve when the fragment is paused or stopped, then resumed.

 onCreateView ()

The system calls this when it’s moment in time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you ought to return aView from this procedure that is the root of your fragment’s layout. You can return null if the fragment does not create a UI.

 onPause ()

The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). This is typically where you ought to commit any changes that ought to be persisted beyond the present user session (due to the fact that the user may not come back). The majority of applications ought to put into practice at least these three methods for every fragment, but there are a lot of other callback methods you ought to as well make use of to take care of the many stages of the fragment lifecycle.

There are as well some subclasses that you may want to extend, rather than the base Fragment class:


This displays a floating dialog. Creating a dialog with this class is a good substitute to the use of dialog helper procedures in the Activity class, due to the fact that you can integrate a fragment dialog into the back stack of fragments managed by the activity, permitting the user to return to a dismissed fragment.


This shows a list of items that are handled by an adapter (like a SimpleCursorAdapter), similar to ListActivity. It makes available a lot of methods for managing a list view, like the onListItemClick ()callback to handle click events.


This shows a pecking order of Preference objects as a list, similar to PreferenceActivity. This is useful when producing a “settings” activity for your application.

Adding a user interface

A fragment is typically used as part of an activity’s user interface and supplies its own layout to the activity.

To make available a layout for a fragment, you ought to put into practice the onCreateView () callback method, which the Android system calls whenever it’s time for the fragment to draw its layout. Your implementation of this method ought to return a View that is the root of your fragment’s layout.

Important Note: If your fragment is a subclass of ListFragment, the default execution returns a ListView from onCreateView (), therefore you don’t need to implement it.

To send back a layout from onCreateView (), you can blow it up from a layout resource defined in XML. To help you do so, onCreateView () make available  a LayoutInflater object

To produce a dynamic and multi-pane user interface on Android, you are required to sum up UI components and activity behaviors into modules that you can switch into and out of your activities. You can generate these modules with the Fragment class, which behaves rather like a nested activity that can delineate its own layout and handle its own lifecycle.

When a fragment indicates its own layout, it can be configured in diverse combinations with other fragments inside an activity to change your layout configuration for different screen sizes (a small screen may show one fragment at a time, but a large screen can illustrate two or more).

This class illustrates to you how to produce a dynamic user experience with fragments and optimize your app’s user experience for devices with various screen sizes, all while continuing to sustain devices running versions as old as Android 1.6.

Generating a Fragment

A fragment is a modular section of an activity, which possesses its own lifecycle, receives its own input events, and which you can add or remove while the activity is running. It is something like a “sub activity” that you can reuse in different activities. This lesson illustrates how to broaden the Fragment class with the use of the Support Library so your app remains well-matched with devices running system versions as low as Android 1.6.

Important Note: If you choose that the minimum API level your app needs is 11 or higher, you don’t supposed to use the Support Library and can as an alternative use the framework’s built in Fragment class and associated APIs. Just know that this lesson is focused on using the APIs from the Support Library, which use a particular package signature and sometimes to some extent diverse API names than the versions included in the platform.

Before you begin this lesson, you ought to set up your Android project to make use of the Support Library. If you have not previously make use of  the Support Library, set up your project to use the v4 library by following the Support Library Setup document. Nevertheless, you can as well include the action bar in your activities by as an alternative using the v7 appcompat library, which is well-matched with Android 2.1 (API level 7) and as well includes the Fragment APIs.

Generating a Fragment Class

To generate a fragment, broaden the Fragment class, then overrule key lifecycle methods to insert your app logic, similar to the way you would with an Activity class. One difference when creating a Fragment is that you ought to make use of the onCreateView () callback to define the layout. In short, this is the only callback you require in order to obtain a fragment running. For instance, see a simple fragment that specifies its own layout:

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

public class BlogFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.article_view, container, false);

Just like an activity, a fragment ought to implement other lifecycle callbacks that permit you to manage its state as it is added or removed from the activity and as the activity transitions between its lifecycle states. For example, when the activity’s onPause() procedure is called, any fragments in the activity as well receive a call to onPause()

Add a Comment