How can I get the currently displayed Fragment instance in Android ?



Introduction

Android applications are built using different components such as Activities as well as Fragments. Fragments are lighter versions of activity and hence they are used in most of the cases for displaying the UI of the application. Fragments are considered as one of the essential components of Android application. They are generally used to create a complex, dynamic user interface that is both robust and highly customizable. Managing the Fragments in an android application is a bit tricky and particular when it comes to resuming fragments from the back stack. One activity within an android application can contain multiple fragments to be displayed in it. In this article we will take a look at How we can get the currently displayed Fragment instance in Android.

Implementation

We will be creating a simple project in which we will be displaying a first fragment inside which we will be displaying a text view. We will be displaying this first fragment inside our activity and we will be getting the instance of that fragment within our activity and display the toast message accordingly inside our application.

Step 1: Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note ? Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 3: Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/idRLLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- creating a frame layout for displaying a container-->
   <FrameLayout
      android:id="@+id/frameContainer"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</RelativeLayout>

Explanation ? In the above code we are creating a Relative layout as a root layout and inside this we are creating a frame layout in which we will be displaying our first fragment which will contain a text view and a button. On clicking of the button we will be opening a new fragment.

Step 4: Creating a new Fragment

Now we will be creating a first fragment. For creating a new Fragment. Navigate to app>java>your app's package name>Right click on it>New>Fragment and select an Empty Blank Fragment and name it as FragmentOne. After creating a new Fragment two files will be created one is a java file named as FragmentOne.java file and fragment_one.xml file.

Step 5: Working with fragment_one.xml file

Navigate to fragment_one.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>fragment_one.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<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"
   tools:context=".FragmentOne">

   <!-- creating a text view for displaying tezt view on below line-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Welcome to Tutorials Point"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="20sp"
      android:textStyle="bold" />
</RelativeLayout>

Explanation: In the above code we are creating a root layout as Relative layout. Inside this relative layout we are creating a text view for displaying the heading of our application.

Step 6: Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>java>your app's package name>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.androidjavaapp;

import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      // on below line creating and initializing variable for fragment.
      Fragment fragment = new FragmentOne();
      
      // on below line creating and initializing variable for fragment transcation.
      FragmentManager manager = getSupportFragmentManager();
      
      // on below line creating a variable for fragment transaction.
      FragmentTransaction transaction = manager.beginTransaction();
      
      // on below line replacing the transaction with the fragment.
      transaction.replace(R.id.frameContainer, fragment, "FragmentOne");
      
      // on below line adding back stack as null.
      transaction.addToBackStack(null);
      
      // on below line committing changes.
      transaction.commit();
      
      // on below line we are checking weather the current fragment is fragment one
      FragmentOne fragmentOne = (FragmentOne) getSupportFragmentManager().findFragmentByTag("FragmentOne");
      if (fragmentOne != null && fragmentOne.isVisible()) {

         // if it is fragment one we are displaying a toast message.
         Toast.makeText(this, "Fragment One is visibile", Toast.LENGTH_SHORT).show();
      }

   }
}

Explanation ? In the above code we can see the onCreate method inside which we are inflating our layout for activity_main.xml. Inside this onCreate method we are loading our FragmentOne and adding backStack for this as well as null. After that we are creating one more variable for fragment one in that variable we are checking weather the fragment which is present in our frame layout is FragmentOne or not. If that is fragment one then we are displaying a toast message as Fragment One is visible.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note ? Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above tutorial we have taken a look on How we can get the currently displayed fragment instance within an android application.

Updated on: 2023-03-30T12:46:00+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements