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

282,166

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();
Share:
282,166

Related videos on Youtube

Wun
Author by

Wun

Updated on November 26, 2021

Comments

  • Wun
    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
      Raghunandan over 10 years
      What is this MainActivity.addFragment(LocalFileBrowserFragment.this, fragment)??. you need to add the fragment to backstak and pop the same accordingly
    • Wun
      Wun over 10 years
      There has add the fragment in function addFragment.
    • Raghunandan
      Raghunandan over 10 years
      add fragment to what and an activity method??
    • Viswanath Lekshmanan
      Viswanath Lekshmanan about 9 years
      getActivity().onBackPressed(); can do this
  • Viswanath Lekshmanan
    Viswanath Lekshmanan about 9 years
    getActivity().onBackPressed(); Thik this will do what you have explained.
  • Le_Enot
    Le_Enot almost 9 years
    @suomi35 no. When you need override onBackPressed() you'll face problems with such realization
  • Admin
    Admin over 8 years
    Not seems works. in 2016, into setNavigationOnClickListener not works.
  • Francisco Romero
    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
    Viswanath Lekshmanan almost 8 years
    @Le_Enot There wont be any problem, since onBackPressed() will follow the lifecycle events :)
  • Yash Agrawal
    Yash Agrawal almost 8 years
    for usinf popStackImmediate() :-> getView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { getActivity().getSupportFragmentManager().popBackStackImmedi‌​ate() ; return true; } return false; } });
  • rollstuhlfahrer
    rollstuhlfahrer over 6 years
    While 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.
    Bruno L. over 6 years
    This 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
    Aman Chhabra almost 6 years
    Try 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
    busuu almost 6 years
    this closes the whole activity, not the fragment
  • Zon
    Zon almost 6 years
    It closes Activity as well! Only Fragment closing is required.
  • CoolMind
    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
    Alesha170 almost 5 years
    It helped me. Those who want more information may google it. No need to copypaste here official documentation.
  • Aliton Oliveira
    Aliton Oliveira over 4 years
    If 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.
    Arpit J. over 4 years
    getActivity() can be null lot of times.
  • Tamim Attafi
    Tamim Attafi over 4 years
    @ArpitJ. it's only null before onAttach() is called, a fragment can't live without an activity.
  • Arpit J.
    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
    Nolan Amy almost 4 years
    popBackStack() and popBackStackImmediate() are more direct ways of popping the topmost fragment without simulating a button press. Using onBackPressed() triggers OnBackPressedCallbacks; if in the future you want to handle Back button presses specifically, you'll have to switch to popBackStack()/popBackStackImmediate() to avoid triggering the callbacks programmatically.
  • nibbana
    nibbana over 3 years
    this closes the activity, not the fragment
  • Anon
    Anon over 3 years
    You put this code inside the Fragment's buttons's onclick method.
  • Itay Feldman
    Itay Feldman about 3 years
    Terrible 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
    mufazmi about 3 years
    While 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
    Codist over 2 years
    How can we do this if we have to double backpress to close the activity?
  • Faizan Haidar Khan
    Faizan Haidar Khan over 2 years
    This worked for me context.supportFragmentManager.beginTransaction().remove(thi‌​s@MyFragment).commit‌​()
  • Ben
    Ben about 2 years
    With 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.