2

I have one activity, ActivityA, and 3 fragments, FragmentA, FragmentB, and FragmentC.

To add FragmentA, I use replace, where fragment is a new instance of FragmentA:

getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.frame_layout_fragment, fragment)
        .commit();

In the onCreate method of ActivityA, I do a check for FragmentA creation:

if (savedInstanceState == null) {
    FragmentA fragmentA = FragmentA.newInstance();

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.frame_layout_fragment, fragmentA)
            .commit();
}

To add FragmentB and FragmentC, I use add and addToBackStack, where fragment is either a new instance of FragmentB or FragmentC:

getSupportFragmentManager()
        .beginTransaction()
        .add(R.id.frame_layout_fragment, fragment)
        .addToBackStack(null)
        .commit();

I press the back button while on FragmentC, it shows FragmentB, and pressing the back button while on FragmentB shows FragmentA, as expected. While I was on FragmentC, I rotate the device, and FragmentC still shows, as expected.

However, when I navigate from FragmentC to FragmentA using the 2 presses of the back button, then rotate the device twice, portrait -> landscape -> portrait, add FragmentB, add FragmentC, then I rotate the device once, I expected FragmentC to show, but instead FragmentB shows. When I press the back button once, nothing happens. When I press it again, it navigates back to FragmentA. It seems like FragmentC is present in the back stack, but for some reason its not visible.

Why is FragmentC not visible in this scenario?

catsfw
  • 125
  • 5

1 Answers1

1

I think this answer to another question is your answer too: Difference between add(), replace(), and addToBackStack()

It says:

One more importance difference between add and replace is: replace removes the existing fragment and adds a new fragment. This means when you press back button the fragment that got replaced will be created with its onCreateView being invoked. Whereas add retains the existing fragments and adds a new fragment that means existing fragment will be active and they wont be in 'paused' state hence when a back button is pressed onCreateView is not called for the existing fragment(the fragment which was there before new fragment was added). In terms of fragment's life cycle events onPause, onResume, onCreateView and other life cycle events will be invoked in case of replace but they wont be invoked in case of add.

Community
  • 1
  • 1
CaseyB
  • 24,780
  • 14
  • 77
  • 112
  • Rotating the device calls onCreateView for every fragment in my case. FragmentC is not showing even though onCreateView was called. – catsfw Mar 04 '16 at 02:24