Android Fragment Lifecycle

 Today we will learn about Android Fragment Lifecycle and implement a single activity class consisting of two fragments in the android application.
Table of Contents
    • 0.1 Android Fragment
  • 1 Fragment Lifecycle
    • 1.1 Android Fragment Classes
    • 1.2 Android Fragment onCreateView()
    • 1.3 Android Fragment Example
    • 1.4 Android Fragment Example Code
    • 1.5 Android Fragment Example App

Android Fragment

Fragment class in Android is used to build dynamic User Interfaces. The fragment should be used within the Activity. The greatest advantage of fragments is that it simplifies the task of creating UI for multiple screen sizes. An 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 that 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 depict what happens when a fragment is added to an activity:
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 the 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 initialized in the fragment that depends upon the activity’s onCreate() having completed its work then onActivityCreated() can be used for that initialization 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 a 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() the method gets a LayoutInflater, a ViewGroup, and a Bundle as parameters.
LayoutInflater is a component that can create View instance based on layout XML files. As you can see, the example actually does that by calling layout.inflate().
inflate() the 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 the 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="https://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="https://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 text views 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="https://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="https://schemas.android.com/apk/res/android"
             xmlns:tools="https://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.

Post a Comment

0 Comments