Fragment Lifecycle in Android - GeeksforGeeks

17 Nov, 2020
In Android, the fragment is the part of Activity which represents a portion of 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. Fragments can exist only inside an activity as its lifecycle is dependent on the lifecycle of 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, thus fragment is also termed as sub-activity. Fragments can be added, removed, or replaced dynamically i.e., while 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:
Single Fragment: Display only one single view on the device screen. This type of fragment is mostly used for mobile phones.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 fragment.Fragment Transaction: This kind of fragments supports the transition from one fragment to another at run time. Users can switch between multiple fragments like switching tabs.
Single Fragment: Display only one single view on the device screen. This type of fragment is mostly used for mobile phones.
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 fragment.
Fragment Transaction: This kind of fragments supports the transition from one fragment to another at run time. Users can switch between multiple fragments like switching tabs.
Each fragment has it’s own lifecycle but due to the connection with the Activity it belongs to, the fragment lifecycle is infulenced by the activity’s lifecycle.
Description
Fragments 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:
Statically: Explicitly mention the fragment in the XML file of the activity. This type of fragment can not be replaced during the run time.Dynamically: FragmentManager is used to embed fragments with activities that enable the addition, deletion, or replacement of fragments at run time.
Statically: Explicitly mention the fragment in the XML file of the activity. This type of fragment can not be replaced during the run time.
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
Click on File, then New => New Project.Choose Empty activitySelect language as JavaSelect the minimum SDK as per your need.
Click on File, then New => New Project.
Choose Empty activity
Select language as Java
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 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();    }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
CardView in Android With Example
Content Providers in Android with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples