0

I have a container view in an activity to which I have added FragmentA and added it to the backStack. Now, based on some button click I want FragmentA to be replaced in the same container view with FragmentB. But I want to make sure that FragmentA comes back to the UI when back is pressed from FragmentB.

I am confused and so could someone please explain how to handle the above scenario.

Thanks. Sunny

Sunny
  • 7,444
  • 22
  • 63
  • 104

2 Answers2

0

Add the Fragment's to backstack. transaction.addToBackStack(null);

Quoting docs

By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.

More info @ Performing Fragment Transactions in

http://developer.android.com/guide/components/fragments.html

You can check this further

Difference between add(), replace(), and addToBackStack()

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • that is what i did but it didnt seem to work. Ok let me try again. Btw, how is replace different from detach/attach? – Sunny Mar 28 '14 at 15:18
  • @Sunny read the docs and check this http://stackoverflow.com/questions/18634207/difference-between-add-replace-and-addtobackstack – Raghunandan Mar 28 '14 at 15:18
0

You need to add FragmentB to the backstack as well on the FragmentTransaction that replaces FragmentA with FragmentB

Emmanuel
  • 13,083
  • 4
  • 39
  • 53
  • ok great it finally worked. one add on question though...when i press back key it comes back to prev fragment (A) but when i press back on the action bar the whole activity disappers – Sunny Mar 28 '14 at 15:25
  • That is the correct behavior if the `Activity` in question is the only `Activity` left on the `Activity` backstack. Check this link regarding [Up Navigation](http://developer.android.com/training/implementing-navigation/ancestral.html) – Emmanuel Mar 28 '14 at 15:29