How to close the current fragment by using Button like the back button?
Solution 1
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.
Solution 2
I change the code from getActivity().getFragmentManager().beginTransaction().remove(this).commit();
to
getActivity().getFragmentManager().popBackStack();
And it can close the fragment.
Solution 3
For those who need to figure out simple way
Try getActivity().onBackPressed();
Solution 4
getActivity().onBackPressed
does the all you need. It automatically calls the onBackPressed method in parent activity.
Solution 5
simply close the activity
getActivity().onBackPressed();
Related videos on Youtube
Wun
Updated on November 26, 2021Comments
-
Wun over 2 years
I have try to close the current fragment by using Imagebutton.
I am in Fragment-A and it will turn to the Fragment-B when I click the button.
And when I click the button at Fragment-B , it will turn to the Fragment-C and close the Fragment-B.
If I click the back button at Fragment-C , it will back to the Fragment-A.
The code I have try is like the following
camera_album = (ImageButton) view.findViewById(R.id.camera_album); camera_album.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { closefragment(); Fragment fragment = FileBrowserFragment.newInstance(null, null, null) ; MainActivity.addFragment(LocalFileBrowserFragment.this, fragment) ; } }); private void closefragment() { getActivity().getFragmentManager().beginTransaction().remove(this).commit(); }
When I click the back button at fragment-B , it turn to the Fragment-C.
But when I click the back button on Fragment-C , it doesn't back to the Fragment-A. It back to the empty background. If I want to back to Fragment-A , I have to click the back button once again.
SO , it seem doesn't close the current fragment complete.
How to finish the current fragment like the back button of Android ?
-
Raghunandan over 10 yearsWhat is this
MainActivity.addFragment(LocalFileBrowserFragment.this, fragment)
??. you need to add the fragment to backstak and pop the same accordingly -
Wun over 10 yearsThere has add the fragment in function addFragment.
-
Raghunandan over 10 yearsadd fragment to what and an activity method??
-
Viswanath Lekshmanan about 9 yearsgetActivity().onBackPressed(); can do this
-
-
Viswanath Lekshmanan about 9 yearsgetActivity().onBackPressed(); Thik this will do what you have explained.
-
Le_Enot almost 9 years@suomi35 no. When you need override onBackPressed() you'll face problems with such realization
-
Admin over 8 yearsNot seems works. in 2016, into setNavigationOnClickListener not works.
-
Francisco Romero almost 8 years@ViswanathLekshmanan I think this should be an answer instead of a comment. And the accepted answer, in addition.
-
Viswanath Lekshmanan almost 8 years@Le_Enot There wont be any problem, since
onBackPressed()
will follow the lifecycle events :) -
Yash Agrawal almost 8 yearsfor usinf popStackImmediate() :-> getView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { getActivity().getSupportFragmentManager().popBackStackImmediate() ; return true; } return false; } });
-
rollstuhlfahrer over 6 yearsWhile this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
-
Bruno L. over 6 yearsThis simple code actually removes the current fragment view by a OK or Close button on it. I use it for quitting a light setting panel displayed as a Fragment and go back to the Activity. Sorry for this trick but under Android 8, I think it is not so practical to manage multiple Fragment.
-
Aman Chhabra almost 6 yearsTry explaining your answer more , so that its easy for OP and other people to understand the answer who come back to this question in future
-
busuu almost 6 yearsthis closes the whole activity, not the fragment
-
Zon almost 6 yearsIt closes Activity as well! Only Fragment closing is required.
-
CoolMind over 5 years@FranciscoRomero, I suppose, Le_Enot is right. If you overrode
onBackPressed
in the activity, you would get another behaviour. For instance, if you use WebView in a fragment that can move backward in web pages, you won't close the fragment, but will move to a previous page. -
Alesha170 almost 5 yearsIt helped me. Those who want more information may google it. No need to copypaste here official documentation.
-
Aliton Oliveira over 4 yearsIf you are using BottomNavigationView which usually has one activity, this command will close the app instead of getting back to the previous fragment.
-
Arpit J. over 4 yearsgetActivity() can be null lot of times.
-
Tamim Attafi over 4 years@ArpitJ. it's only null before onAttach() is called, a fragment can't live without an activity.
-
Arpit J. over 4 years@TamimAttafi True, but I was referring to cases like rotation or activity is finished and due to some reason fragment instance is still there then it will return null.
-
Nolan Amy almost 4 years
popBackStack()
andpopBackStackImmediate()
are more direct ways of popping the topmost fragment without simulating a button press. UsingonBackPressed()
triggersOnBackPressedCallback
s; if in the future you want to handle Back button presses specifically, you'll have to switch topopBackStack()
/popBackStackImmediate()
to avoid triggering the callbacks programmatically. -
nibbana over 3 yearsthis closes the activity, not the fragment
-
Anon over 3 yearsYou put this code inside the Fragment's buttons's onclick method.
-
Itay Feldman about 3 yearsTerrible solution. Altho it gives the results initially, it can cause many problems once you start overriding OnBackPress or if let's say the keyboard is open or something, the back press you initiate will only close the keyboard not the fragment. And these are only a few of the many possible problems you can encounter with this solution. User popBackStack() or popBackStackImmediate().
-
mufazmi about 3 yearsWhile this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
-
Codist over 2 yearsHow can we do this if we have to double backpress to close the activity?
-
Faizan Haidar Khan over 2 yearsThis worked for me context.supportFragmentManager.beginTransaction().remove(this@MyFragment).commit()
-
Ben about 2 yearsWith fragment of type androidx.fragment.app.Fragment, this seems to leave the fragment header. Therefore I have my main app, with the popped fragment header still showing. The getActivity().onBackPressed() seem to work better for me.