Android Fragment Lifecycle

Filed Under: Android

Today we will learn about Android Fragment Lifecycle and implement a single activity class consisting of two fragments in android application.

Android Fragment

Fragment class in Android is used to build dynamic User Interfaces. Fragment should be used within the Activity. A greatest advantage of fragments is that it simplifies the task of creating UI for multiple screen sizes. A activity can contain any number of fragments.

An Android fragment is not by itself a subclass of View which most other UI components are. Instead, a fragment has a view inside it. It is this view which is eventually displayed inside the activity in which the fragment lives.

Because an android fragment is not a view, adding it to an activity looks somewhat different than adding a view (e.g. TextView). A fragment is added to a ViewGroup inside the activity. The fragment’s view is displayed inside this ViewGroup.

The following diagram shows depicts what happens when a fragment is added to an activity:

android fragment

First the activity obtains a reference to the fragment. Then it gets a reference to the ViewGroup the fragment’s view will be rendered inside. Then the activity adds the fragment. The fragment then creates its view and returns it to the activity. The view is then inserted into the ViewGroup parent, and the fragment is alive.

Fragment Lifecycle

Android fragment lifecycle is illustrated in below image.

android fragment lifecycle

Below are the methods of fragment lifecycle.

  1. onAttach() :This method will be called first, even before onCreate(), letting us know that your fragment has been attached to an activity. You are passed the Activity that will host your fragment
  2. onCreateView() : The system calls this callback when it’s time for the fragment to draw its UI for the first time. To draw a UI for the fragment, a View component must be returned from this method which is the root of the fragment’s layout. We can return null if the fragment does not provide a UI
  3. onViewCreated() : This will be called after onCreateView(). This is particularly useful when inheriting the onCreateView() implementation but we need to configure the resulting views, such as with a ListFragment and when to set up an adapter
  4. onActivityCreated() :This will be called after onCreate() and onCreateView(), to indicate that the activity’s onCreate() has completed. If there is something that’s needed to be initialised in the fragment that depends upon the activity’s onCreate() having completed its work then onActivityCreated() can be used for that initialisation work
  5. onStart() : The onStart() method is called once the fragment gets visible
  6. onPause() : The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session
  7. onStop() : Fragment going to be stopped by calling onStop()
  8. onDestroyView() : It’s called before onDestroy(). This is the counterpart to onCreateView() where we set up the UI. If there are things that are needed to be cleaned up specific to the UI, then that logic can be put up in onDestroyView()
  9. onDestroy() : onDestroy() called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.
  10. onDetach() : It’s called after onDestroy(), to notify that the fragment has been disassociated from its hosting activity

Android Fragment Classes

Fragments were added to the Android API in Honeycomb(API 11).

  1. android.app.Fragment : The base class for all fragment definitions
  2. android.app.FragmentManager : The class for interacting with fragment objects inside an activity
  3. android.app.FragmentTransaction : The class for performing an atomic set of fragment operations
  4. When using a compatibility package library provided by Google, the following classes are used for implementation.

    • android.support.v4.app.FragmentActivity : The base class for all activities using compatibility-based fragment (and loader) features
    • android.support.v4.app.Fragment
    • android.support.v4.app.FragmentManager
    • android.support.v4.app.FragmentTransaction

Android Fragment onCreateView()

Here’s a sample fragment using onCreateView() for its implementation:


public class SampleFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_sample, parentViewGroup, false);
        return rootView;
    }
}

onCreateView() method gets a LayoutInflater, a ViewGroup and a Bundle as parameters.

LayoutInflater is an component which can create View instance based on layout XML files. As you can see, the example actually does that by calling layout.inflate().

inflate() method takes three parameters: The id of a layout XML file (inside R.layout), a parent ViewGroup into which the fragment’s View is to be inserted, and a third boolean telling whether the fragment’s View as inflated from the layout XML file should be inserted into the parent ViewGroup. In this case we’ll pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call. When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .

ViewGroup parameter of onCreateView() is the parent ViewGroup into which the View of the fragment is to be inserted. This is a ViewGroup inside the activity that will “host” the fragment.

Bundle parameter of onCreateView() is a Bundle in which the fragment can save data, just like in an Activity.

Android Fragment Example

Android fragments example project comprises of a single activity holding two fragments: TextFragment and MenuFragment respectively.

android fragment example

Android Fragment Example Code

The MainActivity holds the two fragments TextFragment and MenuFragment. So lets begin with defining the fragments in the xml layout

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="1.0">

    <fragment
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        class="journaldev.com.fragments.fragments.MenuFragment"
        android:id="@+id/fragment"
        android:layout_weight="0.5"/>
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="journaldev.com.fragments.fragments.TextFragment"
        android:id="@+id/fragment2"
        android:layout_weight="0.5"/>
</LinearLayout>

As we can see the class files of the fragments that are a part of this activity are defined as class=”journaldev.com.fragments.fragments.TextFragment”

The fragment classes and their layouts are defined as shown in the snippets below.


package journaldev.com.fragments.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import journaldev.com.fragments.R;
public class TextFragment extends Fragment {
    TextView text,vers;

    @Override

    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.text_fragment, container, false);
        text= (TextView) view.findViewById(R.id.AndroidOs);
        vers= (TextView)view.findViewById(R.id.Version);


        return view;

    }
    public void change(String txt, String txt1){
        text.setText(txt);
        vers.setText(txt1);

    }
}

text_fragment.xml


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:gravity="center"
    android:background="#5ba4e5"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40px"
        android:textColor="#ffffff"
        android:layout_gravity="center"
        android:id="@+id/AndroidOs"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="30px"
        android:id="@+id/Version"/>

</LinearLayout>

The TextFragment comprises of textviews holding the android version name and number.


package journaldev.com.fragments.fragments;

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import journaldev.com.fragments.R;
public class MenuFragment extends ListFragment {
    String[] AndroidOS = new String[] { "Cupcake","Donut","Eclair","Froyo","Gingerbread","Honeycomb","Ice Cream SandWich","Jelly Bean","KitKat" };
    String[] Version = new String[]{"1.5","1.6","2.0-2.1","2.2","2.3","3.0-3.2","4.0","4.1-4.3","4.4"};
    @Override

    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.list_fragment, container, false);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, AndroidOS);
        setListAdapter(adapter);

        return view;

    }
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        TextFragment txt = (TextFragment)getFragmentManager().findFragmentById(R.id.fragment2);
        txt.change(AndroidOS[position],"Version : "+Version[position]);
        getListView().setSelector(android.R.color.holo_blue_dark);
    }
}

list_fragment.xml


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/list" />
</LinearLayout>

The MenuFragment displays a ListView. As we can see here, the layout of ListView is default simple_list_item_1 opposed to the custom layout we created for the ListView in the previous article.

The MainActivity invokes the setContentView from the onCreate Method, that’s it. The fragments are called from the xml file.

Alternatively we can add the fragments from the activity class using FragmentManager as shown in the snippet below:


getFragmentManager()
                  .beginTransaction()
                  .add(R.id.fragmentParentViewGroup, new MyFragment())
                  .commit();

Here the id fragmentParentViewGroup belongs to the FrameLayout shown below:


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:id="@+id/fragmentParentViewGroup"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context=".MyActivity"
             tools:ignore="MergeRootFrame" />

Android Fragment Example App

Below shows the output produced by our project, you can see that two fragments are present here and when you select any one of them in the left side fragment, data gets populated in the right side fragment.

android fragments example, fragment lifecycle

You can download final android fragment project from below link.

Comments

  1. shubham thakare says:

    how to parse data from activity to multiple tab fragments. without their values getting disappeared

  2. Akhila P P says:

    sir what is the difference between a page viewer and a fragment

  3. krishna says:

    hi,

    iam struck in menufragment java class

    iam getting the error inconverible types in text fragment declaration

  4. vaishali says:

    Hi.
    For my web site i need some references, can i provide reference to your web site?

  5. Sheila says:

    Great work Anupam Chugh!!!

  6. Roberto Corona says:

    Great job man!

    A lot of thanks!

  7. Anupam says:

    Using Interfaces.
    A tutorial on this is coming shortly.

  8. aarif ali says:

    how send and receive data one fragments to another data

    1. Anupam says:

      A tutorial on passing data across fragments is coming soon.
      Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages