Bugdr0id Bugdr0id - 1 year ago 93
Android Question

Android fragment simple backstack

I have one activity containing one container that will receive 2 fragments.
Once the activity initialises i start the first fragment with:

showFragment(new FragmentA());

private void showFragment(Fragment fragment) {
.replace(R.id.container, fragment, fragment.getTag())

Then when the user clicks on FragmentA, I receive this click on Activity level and I call:

showFragment(new FragmentB());

Now when I press back button it returns to fragment A (thats correct) and when i press again back button it show empty screen (but stays in the same activity). I would like it to just close the app (since the activity has no parent).

There are a lot of posts related with Fragments and backstack, but i can't find a simple solution for this. I would like to avoid the case where I have to check if im doing back press on Fragment A or Fragment B, since i might extend the number of Fragments and I will need to maintain that method.

Answer Source

You are getting blank screen because when you add first fragment you are calling addToBackStack() due to which you are adding a blank screen unknowingly!

now what you can do is call the following method in onBackPressed() and your problem will be solved

  public void moveBack()
//FM=fragment manager
        if (FM != null && FM.getBackStackEntryCount() > 1)
         }else {


just call the above method!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download