I have the navigation drawer menu structure presently setup to allow for going back to the previous fragmnet, with addToBackStack, when selecting the back button as:
<
Take a look at this: FragmentManager.popBackStack(int, int)
When you commit your fragment transaction, the method returns an identifier for that transaction. Save that int
identifier:
FragmentTransaction xfragmentTransaction = getFragmentManager().beingTransaction();
xfragmentTransaction.replace(R.id.containerView, new MessageTabFragment());
xfragmentTransaction.addToBackStack("MainActivity");
int homeFragmentIdentifier = transaction.commit();
then, in your onBackPressed()
method, you can add either of the following lines:
getFragmentManager().popBackStack(homeFragmentIdentifier, 0); // Exclusive
or
getFragmentManager().popBackStack("MainActivity", 0); // Exclusive
This will pop the back stack all the way back to the supplied identifier. Alternatively, if you want to include the homeFragmentIdentifier
in the "pop"ing, instead of 0
use FragmentManager.POP_BACK_STACK_INCLUSIVE
for the 2nd parameter.
You still must call FragmentTransaction.addToBackStack()
. According to the docs:
public abstract int commit () ... Returns the identifier of this transaction's back stack entry, if addToBackStack(String) had been called. Otherwise, returns a negative number.
Also, if you set the tag of the fragment when adding it to the backstack, for example:
transaction.add(yourFragment);
transaction.addToBackStack("[YourFragmentTransactionTag]");
You can use the alternate method: FragmentManager.popBackStack(String, int) by supplying the tag you used when adding the transaction to the backstack.
getFragmentManager().popBackStack("[YourFragmentTransactionTag]", 0);