Manage The Backstack In Android
Solution 1:
You're going to need to be smart when you are changing the fragments and popBackStack
at the appropriate times in order to control the stack. Here's an example from one of my applications (also handles reusing existing fragments in the stack):
// Idea from http://stackoverflow.com/questions/18305945/how-to-resume-fragment-from-backstack-if-existsprivatevoidsetPrimaryContentFragment(BaseFragment fragment, boolean allowStack){
finalStringbackStackName= fragment.getBackStackName();
finalFragmentManagermanager= getSupportFragmentManager();
finalbooleanfragmentPopped= manager.popBackStackImmediate(backStackName, 0);
if (!fragmentPopped) { //fragment not in back stack, create it.if (!allowStack && manager.getBackStackEntryCount() > 1) {
manager.popBackStack(manager.getBackStackEntryAt(0).getId(), 0);
}
finalFragmentTransactiontransaction= manager.beginTransaction();
transaction.replace(R.id.primary_content, fragment);
transaction.addToBackStack(backStackName);
transaction.commit();
try {
manager.executePendingTransactions();
} catch (IllegalStateException exception) {
// Move along as this will be resolved async
}
}
}
The getBackStack()
method is implemented in my base fragment and has a default implementation of:
public String getBackStackName() {
return getClass().getName();
}
The allowStack
flag is used to control whether there can be more than one entry in the backstack.
As far as inserting the Product fragment when a user navigates directly to a detail page you'll likely need to do just that. ie: Execute a replace for Products and then a replace for Product details. Hopefully this code snippet and the linked post will help you come up with the solution you need.
Solution 2:
The hard back button will always traverse the stack which is its expected behavior from your users.
If you are looking for something that will take you back to a parent activity, like Product X going back to the parent Products screen, that is something you can define using the Up button functions. Up Navigation from Android Dev Site
This way you don't have to try and clear and manage the back stack, just define items that will take the user back to Parent screens.
Post a Comment for "Manage The Backstack In Android"