Michael Schmidt Michael Schmidt - 1 year ago 109
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:

.replace(R.id.container, new AddressFragment())

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 Source

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download