0

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) {
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, fragment, fragment.getTag())
            .addToBackStack(fragment.getTag())
            .commit();
}

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.

Bugdr0id
  • 2,962
  • 6
  • 35
  • 59

3 Answers3

0

addToBackStack(fragment.getTag())

use it for fragment B only, not for fragment A

Sachin
  • 107
  • 1
  • 6
0

I think your fragment A is not popped out correctly, try to use add fragment rather replace to have proper back navigation, however You can check count of back stack using:

FragmentManager fragmentManager = getSupportFragmentManager();
int count = fragmentManager.getBackStackEntryCount();

and you can also directly call finish() in activity onBackPressed() when you want your activity to close on certain fragment count.

Muhammad Farhan Habib
  • 1,859
  • 20
  • 23
0

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)
         {
           FM.popBackStack();
         }else {
           finish();
         }
    }

DO NOT CALL SUPER IN ONBACKPRESSED();

just call the above method!

Satish Silveri
  • 393
  • 4
  • 9
  • my problem was that i didn't realize that i was adding a blank screen to back stack without knowing :/ Then checking if FM.getBackStackEntryCount()>1 solves the problem. Thanks! – Bugdr0id Nov 24 '16 at 11:43
  • Fragment concept is very tricky and vast!! anyways glad could help! – Satish Silveri Nov 24 '16 at 11:45