Open In App

How to Implement onBackPressed() in Fragments in Android?

Last Updated : 09 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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
   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 
   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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads