Fragment In Android

Whenever there is a large screen for an Android
app, there is Fragment to help you out.

In this post, I am going to cover important points on fragments, that will help to any android developer to use fragments quickly.

What is fragment ?

Fragment is modular section of an activity, which has its own lifecycle, receives its own input events, can be dynamically or statically added to a layout.

Use cases of fragments


Case 1:

Lets take an example of List of any items & its details, if we consider Handsets, they requires two Activities or two screens, first screen to show List of items & second screen to show details of selected item.

Without fragment we can achieve case 1 by creating two activities & two layouts i.e one with List & other with details of list item.

Case 2:

If we want to achieve same this for large screen devices like Tablets, TV sets then two screen approach like in case 1 is not efficient. For large screen we need to split large screen space into number of section or pane & each section should get designed & coded by using Fragments.

Lets take a look on below attached image, which shows how fragments helpful to achieve above mentioned both cases.

In above example two fragments are used i.e Fragment A & Fragment B with their own layouts & with their own lifecycle callbacks. For case 1 i.e for Handset we can use Fragment A to show list of items in one screen or let’s say Activity A & Fragment B to show detail of selected list item in another screen let’s say Activity B.

For large screen or for tablets we can use only one screen to use two fragments to show List of item in one pane & details of selected item list in another pane by using same fragments A & B that are used for Handsets. In this way fragment help us to modularize our layout design & business logic of activities.

How to create a fragment ?

To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop() .

Usually, one should implement at least the following lifecycle methods:


onCreate()

The system calls this when creating the fragment. In this call we can initialize essential components of the fragment that we want to retain when the fragment is paused or stopped, then resumed.


onCreateView()

The system calls this when it’s time for the fragment to draw its user interface for the first time. To draw a UI we must return a View from this method that is the root of fragment’s layout. We can return null if the fragment does not provide a UI.


onPause()

The system calls this method as the first indication that the user is leaving the fragment.


Adding UI to Fragment Class

To provide a layout for a fragment, you must implement the onCreateView() callback method. For example, here’s a subclass of Fragment that loads a layout from the example_fragment.xml file:

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

How to Add Fragment to an Activity ?

We can add Fragment to an Activity in two ways.

 


1.By declaring fragment inside activity’s layout file.

For example, here’s the layout file for an activity with two fragments:

<?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" / >
    <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" / >
</LinearLayout>

In above xml layout each fragments have their own unique ID & unique ID is necessary to perform different operations on added fragment. When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the onCreateView() method for each one, to retrieve each fragment’s layout. The system inserts the View returned by the fragment directly in place of the fragment element.


2.By programmatically add the fragment to Activity

To add fragment to an Activity we simply need to specify a ViewGroup in which to place the fragment. To perform operations or transactions such as add, remove, or replace a fragment we have to use APIs from FragmentTransaction. We can get it from Activity’s scope by using following lines of code:

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

You can then add a fragment using the add() method, specifying the fragment to add and the view in which to insert it.

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

Here R.id.fragment_container this ID represents parent view or container for fragment.
After add transaction don’t forget to commit the transaction.

Advantages of fragments

  1. Modular and reusable activity component i.e single fragment can be used across multiple activities.
  2. With the use fragments an Android app can adapt to a variety of devices and screen sizes with less complexity.
  3. Compatible to android API 1.6 or later, though Google have introduced fragments in Honeycomb API level 11, with Compatibility Package, a Java library we can use fragments from API level 1.6 to latest android OS version.
  4. Easy to achieve good navigation of UI components on screen by using backstack of fragments.
  5. Animated effects available when dynamically adding and removing fragments from the screen.

I am sure that above points are enough to get quick start over fragment.