Mes
Mes

Reputation: 1691

Two separate backstacks for fragments under tabs

Can I have two different back stacks for fragments?

Imagine this case : I have an Activity with two tabs : Tab A and Tab B in my app. When the Activity starts fragment A1 is being displayed under Tab A. Under Tab A there is fragment A1 and from there you can go to fragment A2 and from A2 to fragment A3. Similarly Tab B displays fragment B1 and from there you can go to fragment B2.

    TAB A            TAB B
     A1                B1
     |                 |
     V                 V
     A2                B2
     |
     V
     A3

If fragment A3 is displayed and user clicks back I want him to go to A2 and with back again to A3. Same applies to the fragments under Tab b B.

A use case could be : A1 -> B1 -> B2 -> A2 -> A3 and then clicking back will result to A3 -> A2 -> A1 and if user changes Tab to B he should be able to navigate from B2 to B1.

Is this possible ? Is there a way I can have two different back stacks so I can navigate back ? What's the simplest way to do something like that ? Thank you

Upvotes: 0

Views: 95

Answers (1)

Srikanth
Srikanth

Reputation: 1575

  1. Create a map for maintain tabs and it's curresponding fragments:
    Map<String, List<Fragment>> fragmentsStack = new HashMap<String, List<Fragment>>();

  2. Create own tablistener to handle switching to and from that tab,and set it to all tabs. In tablistener onTabSelected set current selected tab to that, and if it is first time, show default fragment otherwise previously selected fragment from that tab.
    @Override public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) { mainActivity.setCurrentSelectedTabTag(tag); if (tabFirstFragment != null) { Fragment nextFragment = mainActivity.getLastFragment(); fragmentTransaction.replace(android.R.id.content, nextFragment); } else { tabFirstFragment = (SherlockFragment) SherlockFragment.instantiate(mainActivity, fragmentClass.getName()); mainActivity.createStackForTab(tag); fragmentTransaction.replace(android.R.id.content, tabFirstFragment); mainActivity.addFragmentToStack(tabFirstFragment); } }

    and tab.setTabListener(new TabListener<SportsFragment>( this, "Sports", SportsFragment.class));

  3. When replacing fragment, add it to curresponding stack.
    public void showFragment(Fragment nextFragment) { FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction(); transaction = transaction.replace(android.R.id.content, nextFragment); transaction.commit(); fragmentsStack.get(currentSelectedTabTag).add(nextFragment); }

For more reference, check here.

Upvotes: 1

Related Questions