Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop back press button from going back to each fragment that was opened in the activity?

I am using this to launch a new fragment depending on the screen size of the device.

FragmentManager fragMgr = getSupportFragmentManager();
        releaseInfoFragment release = (releaseInfoFragment)fragMgr.findFragmentById(R.id.release);

            release = releaseInfoFragment.newInstance(url);
            FragmentTransaction xaction = fragMgr.beginTransaction();
            xaction.replace(R.id.release, release)
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .addToBackStack(null)
            .commit();
    }

The problem is when the user presses the back press button, the it goes back to each fragment that was opened during the activities life cycle. How can i make it where it doesnt do this? I just want it to remove the fragment once its pressed the first time, and then go back to the following activity on the second click.

How do i go about doing this?

like image 938
yoshi24 Avatar asked Feb 23 '23 05:02

yoshi24


1 Answers

If you don't want to go back through every Fragment, remove addToBackStack(null) from your transaction. The function call addToBackStack(null) is an instruction to add the Fragment to the back stack.

EDIT

I don't know of any simple way to remove all the Fragments from the back stack. Of the top of my head, I suggest this:

  1. Leave the call to addToBackStack(null) in so that all Fragments are added to the back stack
  2. Override your Activity's onBackPressed() method and use popBackStack() to pop all the Fragments

Looking at the Android documentation for popBackStack(), it looks like there are a couple of nice features that can help you:

POP_BACK_STACK_INCLUSIVE: Flag for popBackStack(String, int) and popBackStack(int, int): If set, and the name or ID of a back stack entry has been supplied, then all matching entries will be consumed until one that doesn't match is found or the bottom of the stack is reached.

and

popBackStack(int id, int flags) Pop all back stack states up to the one with the given identifier.

like image 162
Pikaling Avatar answered May 02 '23 08:05

Pikaling