
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Resume Android Fragment from Backstack
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. In this article we will take a look at How to resume Android Fragment from BackStack if it exists.
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 and a button. We will be displaying this first fragment inside our activity. On clicking the button we will be opening our second fragment and displaying a text view in it.
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 java file named as FragmentOne.java file and fragment_one.xml file. Similarly we have to create one more Blank Fragment named as FragmentTwo. For this fragment as well two files will be created named as fragment_two.xml and FragmentTwo.java 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 First Fragment" android:textAlignment="center" android:textColor="@color/black" android:textSize="20sp" android:textStyle="bold" /> <!-- creating a button to open second fragment --> <Button android:id="@+id/idBtnLoadFragment" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeading" android:layout_margin="20dp" android:text="Open Second Fragment" android:textAllCaps="false" /> </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 and a button to open a new fragment.
Step 6 : Working with fragment_two.xml file.
Navigate to fragment_two.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>fragment_two.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=".FragmentTwo"> <!-- creating a text view for displaying text 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 Second Fragment" android:textAlignment="center" android:textColor="@color/black" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout>
Step 7 : Working with FragmentOne.java file
Navigate to FragmentOne.java. If this file is not visible. To open this file. In the left pane navigate to app>java>your app's package name>FragmentOne.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 androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class FragmentOne extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_one, container, false); // on below line creating and initializing variable for button Button loadFragment = view.findViewById(R.id.idBtnLoadFragment); // on below line adding click listner for our button. loadFragment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line creating and initializing variable for fragment. Fragment fragment = new FragmentTwo(); // on below line creating and initializing variable for fragment transcation. FragmentTransaction transaction = getFragmentManager().beginTransaction(); // on below line replacing the container transaction.replace(R.id.frameContainer, fragment); // on below line adding back stack as null. transaction.addToBackStack(null); // on below line committing the changes. transaction.commit(); } }); return view; } }
Explanation ? In the above code we can see an onCreateView method inside this method we are inflating the layout file which we have to display. After that we are creating and initializing the variable for our button with the id which we have given inside our fragment_one.xml file. After that we are adding a click listener for this button. Inside the click listener method we are opening a second fragment and adding a back stack as null so that when the user presses back from the second fragment he will be navigated to the first fragment.
Step 7 : 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.annotation.SuppressLint; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; 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. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // on below line replacing the transaction with the fragment. transaction.replace(R.id.frameContainer, fragment); // on below line adding back stack as null. transaction.addToBackStack(null); // on below line committing changes. transaction.commit(); } }
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 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

Conclusio
In the above tutorial we have taken a look on How to create Fragments within an android application. How we can navigate between these fragments and How to resume an Android Fragment from BackStack if it exists.