Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaFragment Lifecycle in Android

Fragment Lifecycle in Android

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:

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 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 fragment.
  3. 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.

Fragment Lifecycle

 

Each fragment has it’s own lifecycle but due to the connection with the Activity it belongs to, the 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 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 will be displayed.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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
    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
    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:

RELATED ARTICLES

Most Popular

Recent Comments