Say I have an activity that has fragments added programmatically:
private void animateToFragment(Fragment newFragment, String tag) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, newFragment, tag);
ft.addToBackStack(null);
ft.commit();
}
What is the best way to return to the previous fragment that was visible?
I found Trigger back-button functionality on button click in Android but I'm thinking simulating a back key event isn't the right way to go about it (and I can't get it to work either):
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
Calling finish()
just closes the activity which I'm not interested in.
Is there a better way to go about this?
To elaborate on the other answers provided, this is my solution (placed in an Activity):
Add those line to your onBackPressed() Method. popBackStackImmediate() method will get you back to the previous fragment if you have any fragment on back stack `
`
To make that fragment come again, just add that fragment to backstack which you want to come on back pressed, Eg:
In the above case, I am opening
LoginFragment
whenButton button
is pressed, right now the user is inSignupFragment
. So ifaddToBackStack(TAG)
is called, whereTAG = "SignupFragment"
, then when back button is pressed inLoginFragment
, we come back toSignUpFragment
.Happy Coding!
Look at the
getFragmentManager().popBackStack()
methods (there are several to choose from)http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
Programmatically go back to the previous fragment using following code.
This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.
On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !
Inside activities on back pressed put this:
And launch the other fragment like this: