How to keep only one instance of a fragment, when switching with NavigationDrawer?

后端 未结 4 412

My App starts with a AddressFragment. From the NavigationDrawer I start (amongst others) a new AddressFragment with:

getSupportFragmentManag         


        
4条回答
  •  粉色の甜心
    2020-12-05 15:54

    Step one:

    Optimize current code to allow a Fragment to have his own "TAG"

    getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, new AddressFragment())
                    .addToBackStack(**AddressFragment.class.getName()**)
                    .commit();
    

    Step two:

    Somewhere in your application flow you will need to determine if a fragment exists:

    public static boolean isFragmentInBackstack(final FragmentManager fragmentManager, final String fragmentTagName) {
        for (int entry = 0; entry < fragmentManager.getBackStackEntryCount(); entry++) {
            if (fragmentTagName.equals(fragmentManager.getBackStackEntryAt(entry).getName())) {
                return true;
            }
        }
        return false;
    }
    

    Step three:

    perform fragment action

    if (exists) {
        // Fragment exists, go back to that fragment
        //// you can also use POP_BACK_STACK_INCLUSIVE flag, depending on flow
        mFragmentManager.popBackStackImmediate(AddressFragment.class.getName(), 0);
    
    } else {
        // Fragment doesn't exist
        // STEP 1 + additional backstack management
    }
    

提交回复
热议问题