Skip some fragments onBackPressed

前端 未结 3 1488
[愿得一人]
[愿得一人] 2021-02-05 16:28

I am fairly new with android fragments so please bear with me.

I have a bunch of fragments using a single activity as host.

In my mind, my fragments are grouped

3条回答
  •  清酒与你
    2021-02-05 16:38

    So the key to your solution here is this guy:

    .addToBackStack(null)
    

    Instead of null, you can pass in a String identifier for that particular transaction -- for instance, the class name of the Fragment is what we use (although that doesn't work if you have multiple instances of the same fragment on the backstack):

    .addToBackStack(Fragment1.class.getName())
    

    Then, if you wanted to get back to Fragment1 from Fragment3, just pop using the identifier of the next fragment, and pass the INCLUSIVE flag (which means it will also pop that next fragment that you specified):

    getFragmentManager().popBackStack(
            Fragment2.class.getName(), 
            FragmentManager.POP_BACK_STACK_INCLUSIVE);
    

    Which will play your animations as expected, but as if the fragments in between were never there. The reason I suggest to use the next fragment is because you probably don't want your first fragment transaction on the back stack.

提交回复
热议问题