Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 912
Wun Avatar asked Dec 28 '13 09:12

Wun


People also ask

How do you end a fragment?

If you are using dynamic fragments, set up via a FragmentTransaction , you could run a transaction to replace() the old fragment with the new one.

How do I disable back press in fragment?

Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity: // Disable onBack click requireActivity(). onBackPressedDispatcher. addCallback(this) { // With blank your fragment BackPressed will be disabled. }


2 Answers

I change the code from getActivity().getFragmentManager().beginTransaction().remove(this).commit();

to

getActivity().getFragmentManager().popBackStack(); 

And it can close the fragment.

like image 168
Wun Avatar answered Sep 22 '22 06:09

Wun


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.

like image 40
S.D. Avatar answered Sep 21 '22 06:09

S.D.