Fragment LifeCycle

Android Fragment is the part of activity, it is also known as sub-activity. There can be more than one fragment in an activity. Fragments represent multiple screen inside one activity.
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.

Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle.


Android Fragment Lifecycle Methods defined in below table

Method Description
onAttach(Activity) it is called only once when it is attached with activity.
onCreate(Bundle) It is used to initialize the fragment.
onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns view hierarchy.
onActivityCreated(Bundle) It is invoked after the completion of onCreate() method.
onViewStateRestored(Bundle) It provides information to the fragment that all the saved state of fragment view hierarchy has been restored.
onStart() makes the fragment visible.
onResume() makes the fragment interactive.
onPause() is called when fragment is no longer interactive.
onStop() is called when fragment is no longer visible.
onDestroyView() allows the fragment to clean up resources.
onDestroy() allows the fragment to do final clean up of fragment state.
onDetach() It is called immediately prior to the fragment no longer being associated with its activity.

How to use Fragments?

This involves number of simple steps to create Fragments.

  • First of all decide how many fragments you want to use in an activity. For example let's we want to use two fragments to handle landscape and portrait modes of the device.
  • Next based on number of fragments, create classes which will extend the Fragment class. The Fragment class has above mentioned callback functions. You can override any of the functions based on your requirements.
  • Corresponding to each fragment, you will need to create layout files in XML file. These files will have layout for the defined fragments.
  • Finally modify activity file to define the actual logic of replacing fragments based on your requirement.

Android Fragment Example

Let's have a look at the simple example of android fragment, activity contain three fragment into a single activity.

MainActivity.java
package com.theitbulls.fragmentex;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    }
}


main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="3"
    android:orientation="vertical">

    <fragment
        android:id="@+id/frag1"
        android:name="com.theitbulls.fragmentex.Fragment1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        tools:layout="@layout/fragment1" />

    <fragment
        android:id="@+id/frag2"
        android:name="com.theitbulls.fragmentex.Fragment2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        tools:layout="@layout/fragment2" />

    <fragment
        android:id="@+id/frag3"
        android:name="com.theitbulls.fragmentex.Fragment3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        tools:layout="@layout/fragment3" />
</LinearLayout>

Fragment1.java
package com.theitbulls.fragmentex;

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

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment1 extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment1, container, false);
    }
}


fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:background="@android:color/holo_red_dark">

    <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Fragment1 Demo"
        android:textSize="12pt" />
</RelativeLayout>

As we created Fragment1.java and layout/fragment1.xml, create Fragment2.java, Fragment3.java, layout/fragment2.xml and layout/fragment3.xml and you can download complete code at the end of this page

Download: FragmentExample.zip