Android Fragment Life Cycle

A Fragment represents a reusable portion of your app’s UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own–they must be hosted by an activity or another fragment. The fragment’s view hierarchy becomes part of, or attaches to, the host’s view hierarchy. We can add or remove fragments in an activity while the activity is running.

Activity is the UI of an application through which user can interact and Fragment is the part of the Activity, it is a sub-Activity inside activity which has its own Life Cycle which runs parallel to the Activities Life Cycle.

Fragment Life Cycle

Each Fragment instance has its own lifecycle. When a user navigates and interacts with your app, your fragments transition through various states in their lifecycle as they are added, removed, and enter or exit the screen.

To manage lifecycle, Fragment implements LifecycleOwner, exposing a Lifecycle object that you can access through the getLifecycle() method.

Each possible Lifecycle state is represented in the Lifecycle.State enum.

  • INITIALIZED
  • CREATED
  • STARTED
  • RESUMED
  • DESTROYED

By building Fragment on top of Lifecycle, you can use the techniques and classes available for Handling Lifecycles with Lifecycle-Aware Components. For example, you might display the device’s location on the screen using a lifecycle-aware component. This component could automatically start listening when the fragment becomes active and stop when the fragment moves to an inactive state.

As an alternative to using a LifecycleObserver, the Fragment class includes callback methods that correspond to each of the changes in a fragment’s lifecycle. These include onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy().

Fragment Lifecycle states and their relation both the fragment’s lifecycle callbacks and the fragment’s view Lifecycle.

Following are the list of methods which will perform during the lifecycle of fragment in android applications.

MethodDescription
onAttach()It is called when the fragment has been associated with an activity.
onCreate()It is used to initialize the fragment.
onCreteView()It is used to create a view hierarchy associated with the fragment.
onActivityCreated()It is called when the fragment activity has been created and the fragment view hierarchy instantiated.
onStart()It is used to make the fragment visible.
onResume()It is used to make the fragment visible in an activity.
onPause()It is called when fragment is no longer visible and it indicates that the user is leaving the fragment.
onStop()It is called to stop the fragment using the onStop() method.
onDestoryView()The view hierarchy associated with the fragment is being removed after executing this method.
onDestroy()It is called to perform a final clean up of the fragments state.
onDetach()It is called immediately after the fragment disassociated from the activity.

Create an Application to display various activity in Fragment LifeCycle methods.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <fragment
        android:id="@+id/blankgragment"
        android:name="in.codingtimes.fragment_lifecycle_android.BlankFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/fragment_blank" />




</RelativeLayout>

fragment_blank.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/fragment_lifecycle"
        android:textColor="@color/teal_700"
        android:fontFamily="sans-serif-medium"
        android:textSize="30sp"
        android:textAlignment="center"/>

</FrameLayout>

MainActivity.java

package in.codingtimes.fragment_lifecycle_android;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

BlankFragment.java

package in.codingtimes.fragment_lifecycle_android;

import android.app.Activity;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


public class BlankFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.d("Fragment LifeCycle", "onCreateView Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onCreateView Called",Toast.LENGTH_SHORT).show();
       return inflater.inflate(R.layout.fragment_blank, container, false);

    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d("Fragment LifeCycle", "onAttach Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onAttach Called",Toast.LENGTH_SHORT).show();

    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Fragment LifeCycle", "onCreate Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onCreate Called",Toast.LENGTH_SHORT).show();

    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.d("Fragment LifeCycle", "onDestroy Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onDestroy Called",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onDestroyView(){
        super.onDestroyView();
        Log.d("Fragment LifeCycle", "onDestroyView Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onDestroyView Called",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onDetach(){
        super.onDetach();
        Log.d("Fragment LifeCycle", "onDetach Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onDetach Called",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onPause(){
        super.onPause();
        Log.d("Fragment LifeCycle", "onPause Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onPause Called",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onResume(){
        super.onResume();
        Log.d("Fragment LifeCycle", "onResume Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onResume Called",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onStart(){
        super.onStart();
        Log.d("Fragment LifeCycle", "onStart Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onStart Called",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onStop(){
        super.onStop();
        Log.d("Fragment LifeCycle", "onStop Called");
        Toast.makeText(getActivity(),"Fragment Lifecycle, onStop Called",Toast.LENGTH_SHORT).show();
    }
}

That’s it!
You have successfully completed the post. Do Share : )

Peace Out!

Source Code – https://github.com/Adityaraj-30/Fragment_LifeCycle_Android.git

Also Read – Android Activity Lifecycle


Check Out Deals on -> Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , Swiggy, KFC


One comment

Leave a Reply

Your email address will not be published.