Michael Schmidt Michael Schmidt - 2 months ago 9
Android Question

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

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

getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new AddressFragment())
.addToBackStack(null)
.commit();


But I would rather just go back the first instance. How could I do that?

Or more general, how can I find out, whether an instance of a fragment already exists and then start that, if yes, otherwise create one?

Answer

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");
}
Comments