Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 697
Michael Schmidt Avatar asked Jul 26 '14 14:07

Michael Schmidt


1 Answers

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");
}
like image 185
Simas Avatar answered Sep 22 '22 17:09

Simas