How to Close the Current Fragment by Using Button Like the Back Button

How to close the current fragment by using Button like the back button?

From Fragment A, to go to B, replace A with B and use addToBackstack() before commit().

Now From Fragment B, to go to C, first use popBackStackImmediate(), this will bring back A. Now replace A with C, just like the first transaction.

Close a fragment on button click which is inside that fragment

Just call:


Toolbar back button does not close current Fragment

I believe what your looking for is the NavigationListener for the Toolbar Widget:

mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

but if your using a Theme with an ActionBar and setting a supportActionBar then do something :

public boolean onOptionsItemSelected(MenuItem item) {
return true;

How can I close the fragment?

There's no such thing like close the fragment, but you can remove the fragment from the stack. To pop the fragment use the following inside button click listener


How can I set onClick to close fragment in ImageView?

Remove getActivity() from closefragment()

private void closefragment() {

Tap back button twice to terminate application in Fragment

I solved the problem by writing it in override fun onAttach
Please check the code below

    override fun onAttach(context: Context) {
mContext = context as MainActivity

callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (doubleBackToExitPressedOnce) {
doubleBackToExitPressedOnce = true
Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
context = mContext,
layout = binding.layoutMain,
type = Constants.SnackBarTypes.Warn,
message = mContext.getString(R.string.tap_twice_to_terminate)
requireActivity().onBackPressedDispatcher.addCallback(this, callback)

Related Topics

Leave a reply