HomeAbout MeContact Me
Custom Fragment Backstack in Android
Android
Custom Fragment Backstack in Android
Emanuele Papa
Emanuele Papa
January 31, 2016
1 min

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) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    fragmentStack = new Stack < > ();
  }
  @Override public void onBackPressed() {
    fragmentStack.pop();
    if (fragmentStack.size() == 0) {
      super.onBackPressed();
    } else {
      showFragment(fragmentStack.lastElement(), false);
    }
  }
  public void showFragment(Fragment fragment, boolean addToStack) {
    if (addToStack) {
      fragmentStack.push(fragment);
    }
    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.


Tags

Previous Article
Auto hide keyboard using Android EditText
Emanuele Papa

Emanuele Papa

Android Developer

Related Posts

Solve ADB stuck on waiting for debugger
Solve ADB stuck on waiting for debugger
November 06, 2022
1 min

Quick Links

HomeAbout MeContact MeRSS Feed

Social Media