Android - limit number of fragments in backStack?

前端 未结 2 1613
余生分开走
余生分开走 2021-02-03 13:36

Currently I have one activity, and fragments are being added to it (search, song details, settings, etc). I implemented side based menu navigation, so now, as a side effect, teh

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-03 14:27

    You can programatically control the number of Fragments in your BackStack:

    FragmentManager fm = getActivity().getSupportFragmentManager();
    
    if(fm.getBackStackEntryCount() > 10) {
    
       fm.popBackStack(); // remove one (you can also remove more)
    }
    

    Simply check how many Fragments there are in your Backstack and remove if there is an "overflow".

    If you want to remove specific Fragments from the BackStack, you will have to implement your own BackStack and override onBackPressed(). Since the Fragment BackStack is a Stack (as the name indicates), only the top element (the last added) can be removed, there is no possibility of removing Fragments in between.

    You could for example use

    ArrayList
    

    to realize your own stack. Simply add and remove Fragments from that "stack" (it's not really a stack anymore) whenever you desire and handle the loading of previous fragments by overriding the onBackPressed() method.

提交回复
热议问题