Vishal Patel
Vishal Patel

Reputation: 2970

Fragment store and reuse : Multiple Child fragments with TabView

Hello I was stuck with multiple fragment store and reuse.

I have 3 Tabs(without viewpager just fragment change) in one Activity and tabs having 2-4 Child fragments as like shown in below image.

so, When I open Activity.
1) Tab1 load and Show F1 fragment.
2) tap on Tab2 and show F1 fragment.
3) tap on button in F1 and move to Tab2's F2 fragment
4) again repeat tap on button at F2 and move to Tab2's F3 Fragment.
5) now I Tap on Tab3 and open F1 fragment.

this 5 working great with backstack null

fragmentTransaction.addToBackStack(null);

but know,

6) when i tap Tab2 It will show F1 fragment always. becase i manage at activity like below snippet.

 switch (selected) {
        case 0:
            showFragment(TAB1.newInstance("", ""), TAG_HOME);
            break;
        case 1:
            showFragment(TAB2.newInstance("", ""), TAG_FAV);
            break;
        case 2:
            showFragment(TAB3.newInstance("", ""), TAG_ADD);
            break;
}

6) I need like, Suppose I tap on Tab2 It show F3 Fragment becase at last time in this tab2 I was Opened F3 fragment.

So How To handle Store tab wise Fragment Backstrack.

And Yes Also need like below step(OnBackpress)

suppouse i am in tab 2 F1 ->F2 ->F3
after back press F3 -> F2(backpress) -> F1(backpress) -> close Activity

enter image description here

Upvotes: 1

Views: 329

Answers (1)

Parag Chauhan
Parag Chauhan

Reputation: 35976

You can store Stack of fragment in Hashmap and retrieve when you change tab.

 HashMap<String, Stack<Fragment>> mStacks = new HashMap<String, Stack<Fragment>>();
 mStacks.put(AppConstants.TAB_A, new Stack<Fragment>());
 mStacks.put(AppConstants.TAB_B, new Stack<Fragment>());
 mStacks.put(AppConstants.TAB_C, new Stack<Fragment>());

While push fragment

 mStacks.get(tag).push(fragment);

While pop fragment

 mStacks.get(mCurrentTab).pop();

For working demo - Github

Upvotes: 1

Related Questions