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

后端 未结 4 408

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

getSupportFragmentManag         


        
4条回答
  •  时光取名叫无心
    2020-12-05 16:20

    When creating the fragment set a tag for it, then later you can find it through the fragment manager and replace/create accordingly.

    FragmentManager fManager = getFragmentManager();
    FragmentTransaction fTransaction = fManager.beginTransaction();
    Fragment fragment = fManager.findFragmentByTag("uniqueTag");
    
    // If fragment doesn't exist yet, create one
    if (fragment == null) {
        fTransaction.add(R.id.fragment_list, new ListFrag(), "uniqueTag");
    }
    else { // re-use the old fragment
        fTransaction.replace(R.id.fragment_list, fragment, "uniqueTag");
    }
    

提交回复
热议问题