The Wayback Machine - https://web.archive.org/web/20240927040257/https://www.geeksforgeeks.org/fragment-lifecycle-in-android/
Open In App

Fragment Lifecycle in Android

Last Updated : 06 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Android, the fragment is the part of the Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the Android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI flexibility on all devices improves the user experience and adaptability of the application. that can exist only inside an activity as its lifecycle is dependent on the lifecycle of the host activity. For example, if the host activity is paused, then all the methods and operations of the fragment related to that activity will stop functioning, the fragment is also termed a sub-activity. Fragments in Android can be added, removed, or replaced dynamically i.e., while the activity is running. 

<fragment> tag is used to insert the fragment in an android activity layout. By dividing the activity’s layout multiple fragments can be added in it.

Below is the pictorial representation of fragment interaction with the activity:

fragment interaction with the activity

Types of Android Fragments

  1. Single Fragment: Display only one single view on the device screen. This type of fragment in android is mostly used for mobile phones.
  2. List Fragment: This Fragment is used to display a list-view from which the user can select the desired sub-activity. The menu drawer of apps like Gmail is the best example of this kind of android fragment.
  3. Fragment Transaction: This kind of fragments in android supports the transition from one fragment in android to another at run time. Users can switch between multiple fragments like switching tabs.

ANdroid Fragment Lifecycle

Each fragment has it’s own lifecycle but due to the connection with the Activity it belongs to, the android fragment lifecycle is influenced by the activity’s lifecycle.

Methods of the Android Fragment

Methods

Description

onAttach()The very first method to be called when the fragment has been associated with the activity. This method executes only once during the lifetime of a fragment.  
When we attach fragment(child) to Main(parent) activity then it call first and then not call this method any time(like you run an app and close and reopen) simple means that this method call only one time.
onCreate()This method initializes the fragment by adding all the required attributes and components.
onCreateView()System calls this method to create the user interface of the fragment. The root of the fragment’s layout is returned as the View component by this method to draw the UI.
You should inflate your layout in onCreateView but shouldn’t initialize other views using findViewById in onCreateView.
onViewCreated()It indicates that the activity has been created in which the fragment exists. View hierarchy of the fragment also instantiated before this function call. 
onStart()The system invokes this method to make the fragment visible on the user’s device.
onResume()This method is called to make the visible fragment interactive.
onPause()It indicates that the user is leaving the fragment. System call this method to commit the changes made to the fragment. 
onStop()Method to terminate the functioning and visibility of fragment from the user’s screen. 
onDestroyView()System calls this method to clean up all kinds of resources as well as view hierarchy associated with the fragment. It will call when you can attach new fragment and destroy existing fragment Resoruce 
onDestroy()It is called to perform the final clean up of fragment’s state and its lifecycle.
onDetach()The system executes this method to disassociate the fragment from its host activity.
It will call when your fragment Destroy(app crash or attach new fragment with existing fragment)

Android Fragment When to call Method

Consider Fragment-1 is A and Fragment-2 is B and A is attached to the Main Activity
              1. If you can replace B with A.
                        A’s call back:
                              onDestroyView()
                              onDestroy()
                              onDetach()

                       B’s call back:
                              onAttach()
                             onCreate()
                             onCreateView()
                            onViewCreated()
 

              2. If you can replace B with A without Losing resources.
                       A’s call back:
                             onDestroy()
                             onDetach()

                      B’s call back:
                             onAttach()
                            onCreate()
                            onCreateView()
                           onViewCreated()
 

Example of Android Fragment

Fragments in android are always embedded in Activities i.e., they are added to the layout of activity in which they reside. Multiple fragments can be added to one activity. This task can be carried out in 2 ways:

  1. Statically: Explicitly mention the fragment in the XML file of the activity. This type of fragment can not be replaced during the run time.
  2. Dynamically: FragmentManager is used to embed fragments with activities that enable the addition, deletion, or replacement of fragments at run time.

Almost all android app uses dynamic addition of fragments as it improves the user experience. Below is the step-by-step implementation of adding 2 fragments in one activity. A default fragment will be visible when the activity appears on the screen and the user can switch between the 2 fragments at the run time. 

Note: Following steps are performed on Android Studio version 4.0

Step 1: Create a new project

  1. Click on File, then New => New Project.
  2. Choose Empty activity
  3. Select language as Java
  4. Select the minimum SDK as per your need.

Step 2: Modify strings.xml file

All the strings which are used in the activity are listed in this file

XML
<resources>
    <string name="app_name">GfG | Fragment in Android</string>
    <string name="heading">Two Fragments in One Activity</string>
    <string name="fragment1_button">Display First Fragment</string>
    <string name="fragment2_button">Display Second Fragment</string>
    <string name="fragment1_text1">Displaying contents of the First Fragment</string>
    <string name="fragment2_text1">Displaying contents of the Second Fragment</string>
</resources>

Step 3: Working with the activity_main.xml file

Open the activity_main.xml file and add 2 buttons to it which will be used to switch between the 2 fragments. Further, add the fragment element in the activity layout. It is the area in which the fragments in android will be displayed.

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:background="#168BC34A"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!-- Heading of the activity -->
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:fontFamily="@font/roboto"
        android:text="@string/heading"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_light"
        android:textSize="24sp"
        android:textStyle="bold" />

    <!-- Button to display first fragment -->
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:background="#4CAF50"
        android:fontFamily="@font/roboto"
        android:onClick="selectFragment"
        android:text="@string/fragment1_button"
        android:textColor="@android:color/background_light"
        android:textSize="18sp"
        android:textStyle="bold" />

    <!-- Button to display second fragment -->
    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="20dp"
        android:layout_marginBottom="20dp"
        android:background="#4CAF50"
        android:fontFamily="@font/roboto"
        android:onClick="selectFragment"
        android:text="@string/fragment2_button"
        android:textColor="@android:color/background_light"
        android:textSize="18sp"
        android:textStyle="bold" />

    <!-- Adding Fragment element in the activity -->
    <fragment
        android:id="@+id/fragment_section"
        android:name="com.example.fragments_backup.FragmentOne"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        tools:layout="@layout/fragment_one" />

</LinearLayout>

The android:name tag under the <fragment> element is containing the file name of default fragment which is to be displayed when activity opens.

Step 4: Creating the two fragment class

These files contain only the onCreateView() method to inflate the UI of the fragment and returns the root of the fragment layout. If the fragment does not have any UI, it will return null.

1. First Fragment class:

Java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentOne extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // inflating the layout of the fragment
        // and returning the view component
        return inflater.inflate(R.layout.fragment_one, container, false);
    }
}

2. Second Fragment Class:

Java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentTwo extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // inflating the layout of the fragment
        // and returning the view component
        return inflater.inflate(R.layout.fragment_two, container, false);
    }
}

Step 5: Creating Layouts for both the fragments

Create two Layout Resource Files for both the fragments. Fragment displays a text on the screen and have a background color to differentiate their area in the Activity layout. Below is the code to implement this layout.

1. fragment_one.xml file:

XML
<?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:background="#5C52CC57"
    android:orientation="vertical">

    <!-- Text to be displayed inside the Fragment -->
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="@string/fragment1_text1"
        android:textAlignment="center"
        android:textColor="@android:color/background_light"
        android:textSize="24sp"
        android:textStyle="bold" />

</LinearLayout>

2. fragment_two.xml file:

XML
<?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:background="#5C3473A6"
    android:orientation="vertical">

    <!-- Text to be displayed inside the Fragment -->
    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fontFamily="@font/roboto"
        android:gravity="center"
        android:text="@string/fragment2_text1"
        android:textAlignment="center"
        android:textColor="@android:color/background_light"
        android:textSize="24sp"
        android:textStyle="bold" />

</LinearLayout>

Step 6: Working with the MainActivity.java file

Now, the functionality of the button to perform operations on clicking will be defined in the MainActivity class. Moreover, the code for the replacement of fragments during run time is also mentioned in this file. Below is the code to implement this step.

Java
import android.os.Bundle;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
    }

    // method for displaying the appropriate
    // fragment according to the clicked button
    public void selectFragment(View view) {

        // creating object for Fragment
        Fragment fr;

        // displaying first fragment
        // if button1 is clicked
        if(view == findViewById(R.id.button1)) {
            fr = new FragmentOne();
        }

        // displaying second fragment
        // if button2 is clicked
        else {
            fr = new FragmentTwo();
        }

        FragmentManager fm = getFragmentManager();

        // fragment transaction to add or replace
        // fragments while activity is running
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_section, fr);

        // making a commit after the transaction
        // to assure that the change is effective
        fragmentTransaction.commit();
    }
}

Output:



Previous Article
Next Article

Similar Reads

Fragment to Fragment Communication in Android using Shared ViewModel
If there are two or more fragments in an activity, they need to communicate and share the data between them. The traditional way of sharing the data between the two fragments is implementing the callback using an interface that is cumbersome and may throw exceptions. But the modern way of doing that is using shared ViewModel. So in this article, it
6 min read
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI flexibility on all devices improves the user experie
4 min read
Dynamic Fragment in Android
Dynamic Fragment is a type of fragment that is defined in an XML layout file and called using FragmentManager class. The FragmentManager class is responsible for managing fragments. It is a part of the Activity and its lifecycle depends on the lifecycle of its container activity. Dynamic Fragments are more responsive and flexible than Static Fragme
4 min read
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It has its own lifecycle and can receive input events a
12 min read
How to Create a New Fragment in Android Studio?
Android Studio is the official integrated development environment for Google's Android operating system, built on JetBrains' IntelliJ IDEA software and designed specifically for Android development. You can Develop Android App using this. Here, We are going to learn how to create a new Fragment in Android Studio. A Fragment is a piece of an activit
2 min read
Difference Between a Fragment and an Activity in Android
An Activity is a user interface component that is mainly used to construct a single screen of the application and represents the main focus of attention on a screen. An activity can host one or more fragments at a time. Fragments, as tablets emerged with larger screens, are reusable components that are attached to and displayed within activities. I
2 min read
Static Fragment in Android
Static Fragment is a type of fragment that is defined in an XML layout file only. It is a part of the Activity and its lifecycle depends on the lifecycle of its container activity. Properties of Static Fragment: Defined using <fragment> tag in XML layout file.Having a fixed position in the Activity's layout.Cannot be removed or replaced at ru
2 min read
How to Save Fragment States with BottomNavigationView in Android?
In Android applications, Activities and Fragments are from the foundation of the UI layer. It is now standard practice to load the UI with multiple fragments. For example, Instagram, Twitter, and a slew of other well-known apps. Imagine browsing some tweets in the Twitter app's HomeFragment, navigating to the search screen, and then returning to th
4 min read
How to Get Current Location Inside Android Fragment?
A Fragment is a piece of an activity that enables more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pan
5 min read
How to Implement GridView Inside a Fragment in Android?
A GridView is a versatile and efficient widget that allows you to display items in a grid-like fashion, perfect for presenting images, icons, or any structured data. Fragments, on the other hand, are essential components for building flexible and modular user interfaces. They enable the creation of reusable UI components that can be combined to cre
5 min read
How to Create Fragment Using Bottom Navigation in Social Media Android App?
This is the Part 2 of "Build a Social Media App in Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to Create Bottom Navigation with 5 Fragments (Home, Users, AddBlog, ChatList, Profile).On HomeFragment we will be Showing all the added blogs.In the UsersFragment, we will be showing all
4 min read
How to Pass Data from Dialog Fragment to Activity in Android?
In many applications, you may have seen that whenever we have to make choices some kind of elevated dialog box appears and ask the user for some input or choice. In this article, we are going to see the same that how we can pass data from a Dialog Box to activity in Android Studio. What we are going to build in this article?In this article, we will
4 min read
How to Send Data From Activity to Fragment in Android?
Prerequisites: Introduction to Activities in AndroidIntroduction to Fragments in AndroidIn Android, a fragment is a portion of the user interface that can be used again and again. Fragment manages its own layout and has its own life cycle. Since fragment is a small portion of the bigger user interface, it can only be initialized inside an activity
5 min read
How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?
In some Android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On the other hand, it provides a different look to that app. It is also possible to provide a different feel like left and right swipes by using ViewPager. And to implement this topic, a few terms are required such as ViewPager,
8 min read
Activity Lifecycle in Android with Demo App
In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when a new activity starts, the previous one always rem
9 min read
Processes and Application Lifecycle in Android
As an android developer, if one does not know the application lifecycle of android application or does not have in-depth knowledge about it, there are very high chances that the application will not have a good user experience. Not having proper knowledge of the application lifecycle will not affect the working of that application but it will lead
7 min read
Understanding Activity Lifecycle to Retain UI Data when Back Pressed in Android
What is onBackPressed() in Android? This is an override function called when the user presses the back button on an Android device. It has great implications on the activity lifecycle of the application. The official documentation states that onBackPressed() method is called when the activity has detected the user's press of the back key. The defau
5 min read
Lifecycle in Android Architecture Components
Lifecycle is one of the Android Architecture Components which was released by Google to make it easier for all the Android developers. The Lifecycle is a class/interface which holds the information about the state of an activity/fragment and also it allows other objects to observe this state by keeping track of it. The LifeCycle component is concer
4 min read
Android Manifest File in Android
Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located in the root directory of its project hierarchy. The manifest file is an important part of our app because it defines the structure and metadata of our application, its components, and its requirements. This file includes nodes for each of the Activities, Se
5 min read
Android | Android Application File Structure
It is very important to know about the basics of Android Studio's file structure. In this article, some important files/folders, and their significance is explained for the easy understanding of the Android studio work environment. In the below image, several important files are marked: All of the files marked in the above image are explained below
3 min read
What's Android Interface Definition Language (AIDL) in Android?
The Android Interface Definition Language (AIDL) is analogous to other IDLs you would possibly have worked with. It allows you to define the programming interface that both the client and repair agree upon so as to speak with one another using interprocess communication (IPC). Traditionally the Android way a process cannot access the memory of some
7 min read
Android | Running your first Android app
After successfully Setting up an Android project, all of the default files are created with default code in them. Let us look at this default code and files and try to run the default app created. The panel on the left side of the android studio window has all the files that the app includes. Under the java folder, observe the first folder containi
3 min read
How to Clone Android Project from GitHub in Android Studio?
Android Studio provides a platform where one can build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto. Android Studio is the official IDE for Android application development, based on IntelliJ IDEA. One can develop Android Applications using Kotlin or Java as the Backend Language, and it provides XML for developing Fro
3 min read
How to Add OpenCV library into Android Application using Android Studio?
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. When it integrated with various libraries,
3 min read
8 Best Android Libraries That Every Android Developer Should Know
Android is an operating system which is built basically for Mobile phones. It is used for touchscreen mobile devices like smartphones and tablets. But nowadays these are utilized in Android Auto cars, TV, watches, camera, etc. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought i
5 min read
How to Add Audio Files to Android App in Android Studio?
The audio file format is a file format for saving digital audio data on a computer system and all are aware of audio files. So in this article, we are going to discuss how can we add audio files to the android app. There are three major groups of audio file formats: Format Name Description Examples Uncompressed audio formatsUncompressed audio forma
3 min read
Different Ways to Change Android SDK Path in Android Studio
Android SDK is one of the most useful components which is required to develop Android Applications. Android SDK is also referred to as the Android Software Development Kit which provides so many features which are required in Android which are given below: A sample source code.An Emulator.Debugger.Required set of libraries.Required APIs for Android
5 min read
How to Capture a Screenshot and Screen Recording of an Android Device Using Android Studio?
Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps. Whenever we are developing an app and in that device, you don't know how to capture screenshot
2 min read
Different Ways to Fix “Select Android SDK” Error in Android Studio
Android SDK is one of the most useful components which is required to develop Android Applications. Android SDK is also referred to as the Android Software Development Kit which provides so many features which are required in Android which are given below: A sample source code.An Emulator.Debugger.Required set of libraries.Required APIs for Android
5 min read
Different Ways to Analyze APK Size of an Android App in Android Studio
APK size is one of the most important when we are uploading our app to Google Play. APK size must be considered to be as small as possible so users can visit our app and download our app without wasting so much data. In this article, we will take a look at How we can analyze our APK in Android Studio to check the APK size. Android Studio itself pro
3 min read
Article Tags :