android - Replacing Fragments not working with addBackStack -


this question understanding behave of function replace() in fragments, in opinion not intuitive.

1) have empty framelayout in xml id = r.id.content_fragment.

2) code, add fragment framelayout usual (i want keep backstack user can go old added fragment)

fragmenttransaction ft = getactivity().getsupportfragmentmanager().begintransaction(); ft.add(r.id.content_fragment, new myfragment1(), "tag1"); ft.addtobackstack(null); ft.commit(); 

3) want replace content of framelayout whole new fragment (notice want replace, expect old fragment disappear backstack)

fragmenttransaction ft = getactivity().getsupportfragmentmanager().begintransaction(); ft.replace(r.id.content_fragment, new myfragment2(), "tag2"); ft.addtobackstack(null); ft.commit(); 

4) when going back, old myfragment1 shown!! how can be? "replace" + "addtobackstack" working simple "add"? why?

thanks

edit:

example:

  • add frag1

  • add frag2

  • add frag3 --> have backstack of 3 fragments

  • replace frag4 --> should have backstack of 1 fragment, i'm replaceing whole content of framelayout frag4

  • add frag5 --> expect have 2 fragments @ backstack (frag4 & frag5)

  • replace frag6 --> expect backstack of 1 again (frag6)


Comments