I'm an android beginner and I'm struggling very hard with a problem which is that: I have an activity which manages 4 fragment. I would like that, when I add a fragment to backStack, it removes the same fragments from backStack (if there is one) in order to have only one time each fragment in backstack. If user goes from A to B to C, and goes back to B, The back stack looks like: C,A instead of C,B,A.
I've looked for a solution to my problem and I've found that a lot of people had the same propblem: Removing a Fragment from the back stack How to avoid adding same fragment to stack The most suggested solution was popBackStackImmediate(String, int) but the enormous problem is that this function removes the stacks on top of the stack that has been popped. This behaviour seems to be unchangeable. So I imagined a solution which consist in run through BackStack through a for loop, and when I have a match beetween my fragments tag and a fragment in BackStack, I delete the stack. I think this stack is a fragmentTransaction so I wondered if it was possible to delete a whole Fragment Tansaction and how to do that :)
private void setFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
String tagFromFragAddedToBackStack = getCurrentFragment().getTag();
String fragmentTag = fragment.getClass().getName();
String fragFromBackStackTag;
FragmentTransaction fragTransFromBackStack;
int i;
for ( i = 0; i < manager.getBackStackEntryCount() ; i++){
fragFromBackStackTag = manager.getBackStackEntryAt(i).getName();
fragTransFromBackStack = (FragmentTransaction) manager.getBackStackEntryAt(i);
fragFromBackStack = manager.findFragmentByTag(fragFromBackStackTag);
if (fragFromBackStackTag == fragmentTag){
// Here, I would like to delete the stack which matches
}
}
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.main_frame, fragment, fragmentTag);
ft.addToBackStack(tagFromFragAddedToBackStack);
ft.commit();
}
private Fragment getCurrentFragment(){
if (homeFragment.isVisible()){
return homeFragment;
}
else if (autonomyFragment.isVisible()) {
return autonomyFragment;
}
else if (shopFragment.isVisible()) {
return shopFragment;
}
else if (accountFragment.isVisible()) {
return accountFragment;
}
else
return null;
}
So I'd expected to have a solution to my global problem which is: when the user clicks sequentially on back button, he doesn't go more than one time on each fragment Thanks :)