popBackStack() after addToBackStack does not work

后端 未结 6 1683
野趣味
野趣味 2021-02-11 20:29

My project contains two fragment :

  • FragmentA : the fragment loaded by default when the app starts
  • FragmentB : replace the fragmentA when a c
6条回答
  •  再見小時候
    2021-02-11 20:50

    The problem is you're mixing Fragment and methods from the support library.

    If you are using the support library, make sure:

    • your Activity extends from the android.support.v4.app.FragmentActivity
    • your Fragment extends from android.support.v4.app.Fragment
    • use getSupportFragmentManager() to get the android.support.v4.app.FragmentManager

    Your code in the Activity would be:

    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
       getSupportFragmentManager().popBackStackImmediate();
    }
    

    Please be aware that if you would like to get the FragmentManager from the Fragment code, you have to use the getFragmentManager method, as explained in the documentation (probably that's the cause of some confusion if you don't have much experience).

    If you are not using the support library:

    • your Activity extends from the android.app.Activity
    • your Fragment extends from android.app.Fragment
    • use getFragmentManager() to get the android.app.FragmentManager

    Your code would be:

    if (getFragmentManager().getBackStackEntryCount() > 0) {
       getFragmentManager().popBackStackImmediate();
    }
    

    fragmentTransaction.commit(); is not necessary in both cases, so remove it.

    Also, please call fragmentTransaction.addToBackStack(null); just before the commit but after the other operations.

提交回复
热议问题