Android - limit number of fragments in backStack?

前端 未结 2 1611
余生分开走
余生分开走 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:23

    This is an old question but my answer might help someone.

    Why not checking if the fragment is in the stack and pop it? This way you wouldn't have to worry with back stack size (unless you have a lot of fragments).

        String backStateName = fragment.getClass().getName();
        boolean fragmentPopped = false;
        try {
            // true if fragment is in the stack
            fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        FragmentTransaction ft = fragmentManager.beginTransaction();
    
        if ( !fragmentPopped ) { //fragment not in back stack, add it...            
            ft.setTransition( FragmentTransaction.TRANSIT_FRAGMENT_FADE );
            ft.replace(R.id.main, fragment);
            ft.addToBackStack( backStateName );
    
            try {
                ft.commit();
            } catch (Exception e) {
                e.printStackTrace();
            }           
        }
    

提交回复
热议问题