In Android, Fragment is a part of an activity which enable more modular activity design. It will not be wrong if we say a fragment is a kind of sub-activity. It represents a behavior or a portion of user interface in an Activity. We can combine multiple Fragments in single Activity to build a multi pane UI and reuse a Fragment in multiple Activities. A fragment must always be embedded in an activity and the fragment’s life-cycle is directly affected by the host activity’s life-cycle.
Recommended read? Activity Life Cycle In Android
Table Of Contents
Fragment Lifecycle In Android:
In Android, Fragments have their own life cycle very similar to an Activity but it has extra events that are particular to the Fragment’s view hierarchy, state and attachment to its activity.
Here is the list of methods which you can to override in your Fragment class −
1. onAttach(): The fragment instance is associated with an activity instance.This method is called first, even before onCreate() method. This method let us know that our Fragment has been attached to an activity.
Below is the example code of onAttach() method.
@Override public void onAttach(Activity activity) { super.onAttach(activity); // add your code here which executes when fragment instance is associated }
2. onCreate(): This will be called when creating the fragment. It means when a new fragment instance initializes, which always happens after it attaches to the host.
Below is the example code of onCreate() method.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // add your code here which executes when fragment's instance initializes }
3. onCreateView(): The will be called when it’s time for the fragment to draw its UI(user interface) for the first time. To draw a UI for our fragment we must return a View component from this method that is the root of our fragment’s layout. We can also return null if the fragment does not provide a UI.
Below is the example code of onCreateView() method.
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_test, container, false); // add your code here to draw the UI for the first time means in this method we can get the reference of the views which are created // in our xml file return v; }
4. onViewCreated(): This will be called after onCreateView() method. This method is particularly useful when inheriting the onCreateView() method implementation but we need to configure the resulting views such as with a ListFragment and when to set up an adapter.
Below is the example code of onViewCreated() method.
@Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // add your code here which executes after the execution of onCreateView() method. }
5. onActivityCreated(): This method is called after the onCreateView() method when the host activity is created. This method indicates that the activity’s onCreate() has completed.
Below is the example code of onActivityCreated() method.
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // add your code here which executes when the host activity is created. }
6. onStart(): This method is called once the fragment gets visible.
Below is the example code of onStart() method.
@Override public void onStart() { super.onStart(); // add your code here which executes when the Fragment gets visible. }
7. onResume(): This method is called when the Fragment is visible and intractable.
Below is the example code of onResume() method.
@Override public void onResume() { super.onResume(); // add your code here which executes when the Fragment is visible and intractable. }
8. onPause(): This method is the first indication that the user is leaving the current fragment or fragment is no longer interactable. It occurs when any Fragment Transition processed or Fragment is removed.
Below is the example code of onPause() method.
@Override public void onPause() { super.onPause(); // add your code here which executes when user leaving the current fragment or fragment is no longer intractable. }
9. onStop(): This method is called after onPause() method.Fragment going to be stopped by calling onStop(). This method calls when the Fragment is no longer visible. it occurs either after the fragment is about to be removed or Fragment Transition is processed(replace Fragment) or when the host activity stops.
Below is the example code of onStop() method.
@Override public void onStop() { super.onStop(); // add your code here which executes Fragment going to be stopped. }
10. onDestroyView(): This method is called when the view and other related resources created in onCreateView() method is removed from the activity’s view hierarchy and destroyed.
Below is the example code of onDestroyView() method.
@Override public void onDestroyView() { super.onDestroyView(); // add your code here which executes when the view's and other related resources created in onCreateView() method are removed }
11. onDestroy(): This method is called to do final clean up of the Fragment’s state but Not guaranteed to be called by the Android platform. This method called after onDestroyView() method.
Below is the example code of onDestroy() method.
@Override public void onDestroy() { super.onDestroy(); // add your code here which executes when the final clean up for the Fragment's state is needed. }
12. onDetach(): This method called after onDestroy() method to notify that the fragment has been disassociated from its hosting activity means Fragment is detached from its host Activity.
Below is the example code of onDetach() method.
@Override public void onDetach() { super.onDetach(); // add your code here which executes when fragment has been disassociated from its hosting activity }
Fragment Lifecycle Example In Android Studio:
Below is the example of Fragment Life Cycle. In this example we show the use of Different callback methods of Fragment. In this we create a Activity and define a Fragment in Activity using <fragment> tag. In our Fragment i.e TestFragment we override all the methods and in each method we set a message that displays in our Log file.
Below you can download code, see final output and step by step explanation of the example:
Step 1: Create a new project and name it IncludeTagExample
Step 2: Open res -> layout ->activity_main.xml (or) main.xml and add following code:
In this step we open xml file and then create a fragment to display the Fragment in our Activity.
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <!-- Take a fragment in our activity --> <fragment android:id="@+id/test_fragment" class="com.fragmentlifecycle.TestFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout="@layout/fragment_test" /> </RelativeLayout>
Step 3: Open src -> package -> MainActivity.java
In this step we don’t add anything because we already add a Fragment from our xml file.
package com.fragmentlifecycle; import android.support.v7.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); } }
Step 4: Now we need a Fragment and a xml layout(xml) file. So create a new Fragment by right click on your package folder and create class and name it TestFragment and add the following code in it.
package com.fragmentlifecycle; import android.annotation.TargetApi; import android.app.Activity; import android.app.Fragment; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @TargetApi(Build.VERSION_CODES.KITKAT) public class TestFragment extends Fragment { private void printLog(String s) { // display a message in Log File Log.d("LifeCycle:", s); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); printLog("onActivityCreated Called"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_test, container, false); printLog("onCreateView Called"); return v; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); printLog("onViewCreated Called"); } @Override public void onAttach(Activity activity) { super.onAttach(activity); printLog("onAttach Called"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); printLog("onCreate Called"); } @Override public void onDestroy() { super.onDestroy(); printLog("onDestroy Called"); } @Override public void onDestroyView() { super.onDestroyView(); printLog("onDestroyView Called"); } @Override public void onDetach() { super.onDetach(); printLog("onDetach Called"); } @Override public void onPause() { super.onPause(); printLog("onPause Called"); } @Override public void onResume() { super.onResume(); printLog("onResume Called"); } @Override public void onStart() { super.onStart(); printLog("onStart Called"); } @Override public void onStop() { super.onStop(); printLog("onStop Called"); } }
Step 5: Now create a new xml layout file by right clicking on res/layout -> New -> Layout Resource File and name it as fragment_test and add the following code in it.
In this step we create a TextView to display a message i.e “Please Check Logcat.!!!” on the screen.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- Create a TextView --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Please Check Logcat.!!!" android:textColor="#000" android:textSize="25sp" /> </LinearLayout>
Output:
Check the logcat in Android Studio and you will see Fragment Lifecycle methods in it.
Thanks for sharing this tutorial in easy language…
How to reuse same fragment for different list across different data data?