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. The Android Fragment States.

  1. Running State: Fragment is visible, its belonged activity is running.
  2. Pause State: If an activity is paused because another not-full-screen activity is displayed at the top of the back stack. This activity-related fragment is paused also.
  3. Stop State: When an activity is stopped, its related fragments are stopped also. FragmentTransaction‘s remove() , replace() method can also make a fragment runs into the stop state. A stopped fragment is invisible, it can be recycled by the 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 the destroy state when you do not call the addToBackStack() method to add the fragment to the back stack.

2. Android Fragment Lifecycle.

  1. When an activity adds a fragment to 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.
  2. The fragment view object does not add into the activity content view directly, this is different from adding other view objects in an activity.
    android-fragments-activity-relations
  3. The below diagram shows fragment lifecycle callback methods for each state.
    android-fragment-lifecycle
  4. Below are the introduction of the activity fragment lifecycle callback methods.
  5. Activity adds fragment use FragmentTransaction‘s add or replace method.
  6. OnAttach: Fragment is attached to the activity.
  7. OnCreate: Fragment is created.
  8. OnCreateView: Fragment view is created, this method will return a view object which is generally the fragment’s root layout view object.
  9. OnActivityCreated: Activity is created. The activity’s OnCreate method has been finished. If you need to do some work after the activity creates in your fragment, you can add those codes here.
  10. OnStart: This method is invoked when the fragment is started until it is visible and ready to interact with the user.
  11. OnResume: This method is called just after OnStart or when the fragment is popup from the back stack, it means the fragment is running again.
  12. OnPause: This method is called when the fragment will be left. Such as when removing the current fragment or replace the current fragment with another fragment.
  13. OnStop: This fragment is going to be stopped. When removing the current fragment or replace the current fragment with another fragment.
  14. OnDestroyView: This method is called before OnDestroy, it is used when you need to clean fragment view objects before destroy.
  15. 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.
  16. 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.

3. Android Fragment Lifecycle Example.

  1. This example will show you the fragment life cycle callback method invoke order. It will print log data in each callback method in the android Logcat monitor console.
  2. To trigger the onPause, onStop, onDestroyView, onDestroy, and onDetach method, you just need to change the android device screen orientation from vertical to horizontal.
  3. Activity java file FragmentLifecycleActivity.java.
    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();
        }
    }
  4. 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" />
  5. 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;
    
    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()");
    
        }
    }
  6. 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>

Leave a Comment

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.