HomeAbout MeContact Me

Custom Fragment Backstack in Android

By Emanuele Papa
Published in Android
January 31, 2016
1 min read
Custom Fragment Backstack in Android

Dealing with Fragments is always a pain: after some time I found a way to deal with them in a less painful way, creating a custom Fragment Backstack.

How to create your custom Fragment Backstack navigation

Put this code in your main Activity:

public class MainActivity extends AppCompatActivity {
  private Stack < Fragment > fragmentStack;
  @Override protected void onCreate(Bundle savedInstanceState) {
    fragmentStack = new Stack < > ();
  @Override public void onBackPressed() {
    if (fragmentStack.size() == 0) {
    } else {
      showFragment(fragmentStack.lastElement(), false);
  public void showFragment(Fragment fragment, boolean addToStack) {
    if (addToStack) {
    getFragmentManager().beginTransaction().replace(R.id.container_fragment, fragment).commit();

We have a fragmentStack field which is a Stack of Fragment: we use this to save the Fragments we show in our app and we initialize it in the onCreate() method of the main Activity.

In the onBackPressed() method we remove the current Fragment from the Stack and then if there is another one, we show it, otherwise we close the app because there is nothing more to be shown.

The method showFragment() is the one we use to show a Fragment on the screen; we invoke it every time we need to change the visible Fragment. If we want to save the current transaction being able to come back to the current Fragment we pass true as addToStack value, otherwise we pass false.

Have a look at the full source code on my GitHub here.


Previous Article
Auto hide keyboard using Android EditText
Emanuele Papa

Emanuele Papa

Android Developer


Smart Home

Related Posts

Clear all Android SharedPreferences
December 29, 2020
1 min

Quick Links

HomeAbout MeContact MeRSS Feed

Social Media