DJ-DOO
DJ-DOO

Reputation: 4779

How to keep state of Parent Fragment

I have a Fragment, in which I have a nested fragment. I've attached an image to illustrate. So I have child a nested, when I click button 1, I replace child A with child B, then on button 2 click I replace child B with child C. Now when I click on button 3, I replace the parent (Fragment 1 with Fragment 2), this is what I want to do.

When I hit the back button when on Fragment 2, I pop the backstack and I display fragment 1, the problem is child A is displayed, I need to figure out how to display child c when I go from Fragment 2 to Fragment 1. I need to mention also that child c contains test results that are displayed in a grid view. Can someone help me do this please?

EDIT

Below is the code I'm using for the transactions for the child fragments (button 1 and button 2 click)

 protected void nextNestedFragment(Fragment nestedFragment){
        FragmentTransaction ft = getParentFragment().getChildFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.animator.enter_slide_in,R.animator.enter_slide_out,R.animator.close_slide_in, R.animator.close_slide_out);
        ft.replace(R.id.nested_fragment_container, nestedFragment).addToBackStack(null).commit();    
    }

So for the above I pass in the next fragment I wish to navigate to within the parent fragment. Below is the code I use on button 3 press to navigate from Fragment 1 to Fragment 2:

  protected void nextFragment(Fragment nextFrag){
        FragmentTransaction ft = getParentFragment().getFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.animator.enter_slide_in,R.animator.enter_slide_out,R.animator.close_slide_in, R.animator.close_slide_out);
        ft.replace(R.id.fragment_container, nextFrag).addToBackStack(null).commit();
    }

enter image description here

Upvotes: 0

Views: 1024

Answers (1)

Ayzen
Ayzen

Reputation: 983

First, you need to know, that you have 2 different FragmentManager here (the default one, and ChildFragmentManager) and each with it's own back stack. And when you press a back button, you pop a back stack of your first FragmentManager, which shows you Fragment 1.

Second, when Fragment 1 is being popped from back stack onCreateView of that fragment is invoked. And I'm pretty sure you are creating a view there with a child A inside.

What you need to do is to save Fragment's state. There are a lot of questions here on how to do this correctly. Start from here.

Upvotes: 1

Related Questions