How to delete a specific fragment from back stack in android

后端 未结 6 830
野趣味
野趣味 2020-12-29 05:09

I have a problem about removing a specific fragment from back stack.My scenario is like this.Fragment-1 is replaced with Fragment-2 and then Fragment-2 is replaced with Frag

6条回答
  •  盖世英雄少女心
    2020-12-29 05:44

    In the backstack you don't have Fragments, but FragmentTransactions. When you popBackStack() the transaction is applied again, but backward. This means that (assuming you addToBackStackTrace(null) every time) in your backstack you have

    1->2
    2->3
    

    If you don't add the second transaction to the backstack the result is that your backstack is just

    1->2
    

    and so pressing the back button will cause the execution of 2->1, which leads to an error due to the fragment 2 not being there (you are on fragment 3).
    The easiest solution is to pop the backstack before going from 2 to 3

    //from fragment-2:
    getFragmentManager().popBackStack();
    getFragmentManager().beginTransaction()
       .replace(R.id.container, fragment3)
       .addToBackStack(null)
       .commit();
    

    What I'm doing here is these: from fragment 2 I go back to fragment 1 and then straight to fragment 3. This way the back button will bring me again from 3 to 1.

提交回复
热议问题