How to Implement onBackPressed() in Fragments in Android?
Last Updated :
26 Apr, 2025
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. onBackPressed() is a method that is to be implemented in our activity in order to run a function after pressing the back button. Usually, onBackPressed() method is used to implement some method after moving back from an activity.
@Override
public void onBackPressed() {
super.onBackPressed();
}
Since there is no override onBackPressed() method to implement in Fragments. There is one method of implementing onBackPressed() method to call the interface method which are implemented in the fragment using onBackPressed() method of the activity containing fragment layout.
Step by Step Implementation
Step 1: Create a java class(Backpreessedlistener) and here, we implement an interface having a method onBackPressed()(any name as we want) and override accordingly.
public interface Backpressedlistener {
void onBackPressed();
}
Step 2: Implement the method of interface write a function to implement on back pressed in the fragment.
@Override
public void onBackPressed() {
Toast.makeText(getContext(),"back button pressed",Toast.LENGTH_LONG).show();
}
Step 3: Create the frame layout in the activity_main.xml file
<FrameLayout
android:id="@+id/fragl"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Step 4: Create the object of the interface.
public class BlankFragment extends Fragment implements Backpressedlistener {
View v;
// creating object of Backpressedlistener interface
public static Backpressedlistener backpressedlistener;
// Driving code
............................
}
Step 5: In an fragment class (BlankFragment) implement onpause() method and onResume() method, pass null to backpressedlistener in onPause() method and context of fragment to backpressedlistener in onResume() method.
// Overriding onPause() method
@Override
public void onPause() {
// passing null value
// to backpressedlistener
backpressedlistener=null;
super.onPause();
}
// Overriding onResume() method
@Override
public void onResume() {
super.onResume();
// passing context of fragment
// to backpressedlistener
backpressedlistener=this;
}
Step 6: In Mainactivity, Implement onBackPressed() method and access the backpressedlistener.
@Override
public void onBackPressed() {
super.onBackPressed();
if(BlankFragment.backpressedlistener!=null){
// accessing the backpressedlistener of fragment
BlankFragment.backpressedlistener.onBackPressed();
}
}
There are the following Layout and code for the Implementation of onBackPressed() in Fragments.
Complete Code
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.Â
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/fragl"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file.
Java
package com.example.gfg;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
public void onBackPressed() {
// super.onBackPressed();
if(BlankFragment.backpressedlistener!=null){
BlankFragment.backpressedlistener.onBackPressed();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.add(R.id.fragl,BlankFragment.class,null)
.commit();
}
}
fragment_blank.xml:
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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=".BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
BlankFragment.java:
Java
package com.example.gfg;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class BlankFragment extends Fragment implements Backpressedlistener {
View v;
public static Backpressedlistener backpressedlistener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_blank, container, false);
return v;
}
@Override
public void onPause() {
backpressedlistener=null;
super.onPause();
}
@Override
public void onResume() {
super.onResume();
backpressedlistener=this;
}
@Override
public void onBackPressed() {
Toast.makeText(getContext(),"back button pressed",Toast.LENGTH_LONG).show();
}
}
Backpressedlistener.java:
Java
package com.example.gfg;
public interface Backpressedlistener {
void onBackPressed();
}
Output:
Similar Reads
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 h
12 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 fl
4 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
5 min read
How to Implement findViewById in Fragments in Android?
Fragments represent a part of the app's UI which is reusable. Fragments are having its own layout, and lifecycle but must be hosted inside an activity to be visible. The activity becomes easier to modify if it consists of many fragments. A fragment can have multiple instances inside an activity. fin
3 min read
How to Implement Press Back Again to Exit in Android?
The 'Back' button has many different uses in many different android apps. While some app developers use it to close their apps, some use it to traverse back to the app's previous activity. Many apps require the user to press the 'Back' button two times within an interval to successfully close the ap
2 min read
How to Implement OnSavedInstanceState in Android?
In android, Preserving and restoring an activity's UI state in a timely fashion across system-initiated activity or application destruction is a crucial part of the user experience. In these cases the user expects the UI state to remain the same, but the system destroys the activity and any state st
4 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
8 min read
How to Implement Item Click Interface in Android?
When we click on an item in an application either it gives some information or it redirects the user to any other page. In this article, we will learn that how we can implement Item Click Interface in an android application. What we are going to build in this article?In this article, we will be usin
5 min read
How to Implement Swipe Down to Refresh in Android
Certain applications show real-time data to the users, such as stock prices, availability of a product on online stores, etc. Showing real-time data requires continuous syncing of the application, and could be possible by implementing a program such as a thread. A Thread could be initiated by the ap
3 min read
How to Implement TNImage Library in Android?
Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android O
3 min read