Fragments and the Back Stack in Android

Fragments enable you to create dynamic Activity layouts that can be modified to present significant changes in the UIs. In some cases these changes could be considered a new screen — in which case a user may reasonably expect the back button to return to the previous layout. This involves reversing previously executed Fragment Transactions.

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
fragmentTransaction.add(R.id.ui_container, new MyListFragment());
Fragment fragment = fragmentManager.findFragmentById(R.id.details_fragment);
fragmentTransaction.remove(fragment);
String tag = null;
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();

Pressing the Back button will then reverse the previous Fragment Transaction and return the UI to the earlier layout.

Leave a Comment