Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically go back to the previous fragment in the backstack

People also ask

How do you resume an existing Backstack fragment?

Since you want only one back stack entry per Fragment , make the back state name the Fragment's class name (via getClass(). getName() ). Then when replacing a Fragment , use the popBackStackImmediate() method. If it returns true, it means there is an instance of the Fragment in the back stack.

How do you ensure that the user can return to the previous fragment by pressing the back button?

fragment_container ID. By calling addToBackStack() , the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.


Look at the getFragmentManager().popBackStack() methods (there are several to choose from)

http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()


To elaborate on the other answers provided, this is my solution (placed in an Activity):

@Override
public void onBackPressed(){
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        Log.i("MainActivity", "popping backstack");
        fm.popBackStack();
    } else {
        Log.i("MainActivity", "nothing on backstack, calling super");
        super.onBackPressed();  
    }
}

When we are updating/add the fragments,

Should Include the .addToBackStack().

getSupportFragmentManager().beginTransaction()
    .add(detailFragment, "detail") // Add this transaction to the back stack (name is an optional name for this back stack state, or null).
    .addToBackStack(null)
    .commit();

After that if we give the getFragments.popBackStackImmediate() will return true if we add/update the fragments, and move back to the current screen.


Android Navigation architecture component.

The following code works for me:

findNavController().popBackStack()

These answers does not work if i don't have addToBackStack() added to my fragment transaction but, you can use:

getActivity().onBackPressed();

from your any fragment to go back one step;