Android Fragment Lifecycle

Android fragment belongs to activity. Like activity, fragment also has it’s own life cycle. In one fragment life cycle, there are four states, running state, pause state, stop state and destroy state. Each state has it’s own call back method in fragment class.

1. Android Fragment States.

  1. Running State : Fragment is visible, it belongs activity is running.
  2. Pause State : If an activity is paused because another not full screen activity is displayed at top of back stack. This activity related fragment is paused also.
  3. Stop State : When an activity is stopped, it related fragments is stopped also. FragmentTransaction’s remove() , replace() method can also make a  fragment runs into stop state. Stopped fragment is invisible, it can be recycled by android OS.
  4. Destroy State : When an activity is destroyed, it’s child fragment is destroyed also. FragmentTransaction’s remove() , replace() method can also make a fragment runs into destroy state when you do not call addToBackStack() method to add the fragment to back stack.

2. Android Fragment Lifecycle.

When an activity add a fragment in it, it will get a reference of the fragment’s view. Then the fragment’s view object will be added into the activity’s viewGroup.

The fragment view do not add into activity content view directly, this is different from adding other view objects in activity.

android fragments activity relations

Below diagram shows fragment lifecycle callback methods for each state.

android fragment lifecycle

  1. Activity add a fragment use FragmentTransaction’s add or replace method.
  2. OnAttach : Fragment is attached to the activity.
  3. OnCreate : Fragment is created.
  4. OnCreateView : Fragment view is created, this method will return a view object which is generally the fragment’s root layout view object.
  5. OnActivityCreated : Activity is created. The activity’s OnCreate method has been finished. If you need to do some work after activity create in your fragment, you can add those code here.
  6. OnStart : This method is invoked when the fragment is started until it is  visible and ready to interact with user.
  7. OnResume : This method is called just after OnStart or when the fragment is popup from the backstack, it means the fragment is running again.
  8. OnPause : This method is called when the fragment will be left. Such as when remove current fragment or replace current fragment with other fragment.
  9. OnStop : This fragment is going to be stopped. When remove current fragment or replace current fragment with other fragment.
  10. OnDestroyView : This method is called before OnDestroy, it is used when you need to clean fragment view objects before destroy.
  11. OnDestroy : This method is called when android OS destroy current fragment, you can do some resource release or state info store action in this method.
  12. OnDetach : When the fragment is destroyed, it will be detached from the activity, if you need to do some work in this state, you can put your code in this method.
READ :   Simple Android News App Compatible With Phones and Tablets

3. Android Fragment Lifecycle Example.

This example will show you the fragment life cycle callback method invoke order. It will print log data in each callback method in android logcat monitor.

To trigger onPause, onStop, onDestroyView, onDestroy and onDetach method, you just need to change the android device screen orientation from vertical to horizontal.

android fragment lifecycle example output

Activity Java File.

FragmentLifecycleActivity

package com.dev2qa.example.fragment.lifecycle;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.dev2qa.example.R;

public class FragmentLifecycleActivity extends AppCompatActivity {

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

        setTitle("dev2qa.com - Fragment Lifecycle Example.");

        FragmentManager fragmentManager = this.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        FragmentLifeCycle fragmentLifeCycle = new FragmentLifeCycle();
        fragmentTransaction.add(R.id.fragment_lifecycle_frame_layout, fragmentLifeCycle, "Lifecycle Fragment");
        fragmentTransaction.commit();
    }
}

Activity Layout Xml File.

activity_fragment_lifecycle.xml

<FrameLayout
    android:id="@+id/fragment_lifecycle_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Fragment Java File.

FragmentLifeCycle.java

package com.dev2qa.example.fragment.lifecycle;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dev2qa.example.R;
import com.dev2qa.example.util.FragmentUtil;

/**
 * Created by Jerry on 12/25/2017.
 */

public class FragmentLifeCycle extends Fragment {

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onAttach()");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onCreate()");

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onCreateView()");
        View retView = inflater.inflate(R.layout.fragment_lifecycle, container, false);
        return retView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onActivityCreated()");

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onStart()");

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onResume()");

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onPause()");

    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onStop()");

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onDestroyView()");

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onDestroy()");

    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(FragmentUtil.TAG_NAME_FRAGMENT, "onDetach()");

    }
}

Fragment Layout Xml File.

fragment_lifecycle.xml

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Fragment lifecycle test."
        android:textSize="20dp"
        android:gravity="center"
        android:textColor="@android:color/holo_red_light"/>

</LinearLayout>
(Visited 2,219 times, 5 visits today)

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.