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:

getActivity().onBackPressed();

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() {
@Override
public void onClick(View v) {
onBackPressed();
}
});

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
onBackPressed();
break;
}
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

getActivity().getFragmentManager().beginTransaction().remove(this).commit();

How can I set onClick to close fragment in ImageView?

Remove getActivity() from closefragment()

private void closefragment() {
getFragmentManager().popBackStack();
}

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) {
super.onAttach(context)
mContext = context as MainActivity

callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (doubleBackToExitPressedOnce) {
activity?.finish()
}
doubleBackToExitPressedOnce = true
Handler().postDelayed({ doubleBackToExitPressedOnce = false }, 2000)
showSnackBar(
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



Submit