2

I have 3 fragments, and I'm navigating using bottom menu (3 items), lets say I navigate this way :

A -> B -> C -> B -> C

when I press the back button, that's what will happen

A <- B <- C <- B <- C

and what I want is this

A <- B <- C

that's mean if add fragment that's already added the old one must be deleted, more precisely remove the transaction from the back stack

this code will not work because we are adding new transaction here :

FragmentTransaction transaction = mContext.beginTransaction();
Fragment lastFragment = mContext.findFragmentByTag(mFragmentTag);
if (lastFragment != null) {
     transaction.remove(lastFragment);
     transaction.commit();
}

btw, may some developers make a mistake, but the back stack stores transactions and NOT fragments.

Abdel
  • 1,005
  • 2
  • 11
  • 24

1 Answers1

0

To get this behaviour, you can follow something like this:

I am assuming you have a onTabSelected(int position) which gets called every time you tap on the bottom menu.

public void onTabSelected(int position, boolean wasSelected) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    // Pop off everything up to and including the current tab 
    fragmentManager.popBackStack(SELECTED_FRAG_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);

    // Add again the new tab fragment
    fragmentManager.beginTransaction()
            .replace(R.id.container, TabFragment.newInstance(),
                    String.valueOf(position)).addToBackStack(SELECTED_FRAG_TAG)).commit();
}

Firstly, you need to have tags for all your fragment. The basic idea is popBackStack upto that fragment tag that is selected.

And from the documentation of popBackStack(String name, int flags)

Pop the last fragment transition from the manager's fragment back stack. If there is nothing to pop, false is returned. This function is asynchronous -- it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.

@param name If non-null, this is the name of a previous back state to look for; if found, all states up to that state will be popped.

The {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether the named state itself is popped. If null, only the top state is popped. @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}.

Ayush Khare
  • 1,802
  • 1
  • 15
  • 26
  • thank you for the response, if I have this case : A -> B -> C -> B, if I click the back button I want this : A <- C <- B; with the solution you suggested I will get this: A <- B. normally I have more fragments inside each tab (detail, settings..) I just simplified the example. you can check the Instagram navigation to understand what I'm looking for. – Abdel Oct 16 '18 at 09:50