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

14

121

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 ?

Ulrick answered 28/12, 2013 at 9:24 Comment(4)
What is this MainActivity.addFragment(LocalFileBrowserFragment.this, fragment)??. you need to add the fragment to backstak and pop the same accordinglyEnglebert
There has add the fragment in function addFragment.Ulrick
add fragment to what and an activity method??Englebert
getActivity().onBackPressed(); can do thisRatline
T
87

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.

Tidbit answered 28/12, 2013 at 9:51 Comment(1)
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().popBackStackImmediate() ; return true; } return false; } });Dilute
U
181

I changed the code from

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

to

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

And it pops out the top fragment

Ulrick answered 28/12, 2013 at 9:36 Comment(4)
This worked for me context.supportFragmentManager.beginTransaction().remove(this@MyFragment).commit()Territoriality
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.Barbee
Don't forget to use "getSupportFragmentManager()" in case "getFragmentManager()" isn't working for youDiondione
Unfortunately this is outdated. Use: OnBackPressedCallback from now on.Cropland
R
88

For those who need to figure out simple way

Try getActivity().onBackPressed();

Ratline answered 26/8, 2016 at 5:57 Comment(7)
getActivity() can be null lot of times.Pyrene
@ArpitJ. it's only null before onAttach() is called, a fragment can't live without an activity.Sclerometer
@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.Pyrene
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.Chamkis
You put this code inside the Fragment's buttons's onclick method.Moil
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().Decoct
'onBackPressed()' is deprecatedVeneering
T
87

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.

Tidbit answered 28/12, 2013 at 9:51 Comment(1)
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().popBackStackImmediate() ; return true; } return false; } });Dilute
C
6

Try this:

public void removeFragment(Fragment fragment){
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.remove(fragment);
    fragmentTransaction.commit();
}
Collayer answered 18/9, 2016 at 1:23 Comment(0)
D
5

This is a Kotlin way of doing this, I have created button in fragment layout and then set onClickListner in onViewCreated.

according to @Viswanath-Lekshmanan comment

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) 
{
     super.onViewCreated(view, savedInstanceState)

     btn_FragSP_back.setOnClickListener {
        activity?.onBackPressed()
    }
}
Derna answered 18/11, 2017 at 14:38 Comment(2)
this closes the activity, not the fragmentVerduzco
How can we do this if we have to double backpress to close the activity?Piquant
A
5

You can try this logic because it is worked for me.

frag_profile profile_fragment = new frag_profile();

boolean flag = false;
@SuppressLint("ResourceType")
public void profile_Frag(){
    if (flag == false) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.setCustomAnimations(R.anim.transition_anim0, R.anim.transition_anim1);
        transaction.replace(R.id.parentPanel, profile_fragment, "FirstFragment");
        transaction.commit();
        flag = true;
    }

}

@Override
public void onBackPressed() {
    if (flag == true) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        manager.getBackStackEntryCount();
        transaction.remove(profile_fragment);
        transaction.commit();
        flag = false;
    }
    else super.onBackPressed();
}
Astomatous answered 19/8, 2018 at 13:50 Comment(0)
D
4

Try this:

ft.addToBackStack(null);   // ft is FragmentTransaction

So, when you press back-key, the current activity (which holds multiple fragments) will load previous fragment rather than finishing itself.

Drucilla answered 28/12, 2013 at 9:50 Comment(0)
J
4
Button ok= view.findViewById(R.id.btSettingOK);
Fragment me=this;
ok.setOnClickListener( new View.OnClickListener(){
    public void onClick(View v){
     getActivity().getFragmentManager().beginTransaction().remove(me).commit();
    }
});
James answered 3/3, 2018 at 12:10 Comment(2)
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.Kero
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.James
S
0

If you need to handle the action more specifically with the back button you can use the following method:

view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            onCloseFragment();
            return true;
        } else {
            return false;
        }
    }
});
Stuffed answered 5/7, 2017 at 10:58 Comment(0)
A
0

In your Fragments onCreateView(...) you can remove a view by calling container.removeView(view);. So if you want to remove the fragment, then view should be the return value of onCreateView,

for example

    public View onCreateView(...){
        final View view = inflater.inflate(R.layout.your_fragments_layout,container,false);
        //Do something
        finishButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                container.removeView(view);
            }
        });
        return view;
    }
Anticoagulant answered 20/5, 2020 at 9:53 Comment(0)
P
0

For remove current fragment B and navigate to stack back (other fragment A):

private fun navigateToBackStack() {
    requireActivity().supportFragmentManager
        .beginTransaction()
        .remove(this)
        .commit()
    requireActivity().supportFragmentManager.popBackStack()
}

GL

Pigfish answered 25/11, 2021 at 15:46 Comment(0)
M
0

If you use JetPack Navigation, write:

findNavController().popBackStack()
Monarch answered 15/3, 2023 at 14:45 Comment(0)
A
0

For those using DialogFragment, just call .dismiss().

Ampliate answered 2/7, 2023 at 19:13 Comment(0)
P
-14

Try this one

getActivity().finish();
Pentarchy answered 9/7, 2018 at 11:29 Comment(4)
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 futureUnnamed
this closes the whole activity, not the fragmentMantic
It helped me. Those who want more information may google it. No need to copypaste here official documentation.Fakir
If you are using BottomNavigationView which usually has one activity, this command will close the app instead of getting back to the previous fragment.Aronow

© 2022 - 2024 — McMap. All rights reserved.