Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a fragment exists and reuse it

I'm using the following code to create a fragment everytime the user click on an item in a list view. But in this way the fragment is created at every user click. What I want is to reuse the old fragment (if it exists) and only reload its content (don't create a new one).

MagazineViewFragment fragment = new MagazineViewFragment();
fragment.openStream(itemSelected);

FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
        .replace(R.id.container,  fragment)
        .commit();

How can I do?

like image 481
Usi Usi Avatar asked Aug 29 '14 11:08

Usi Usi


1 Answers

There're multiple ways, probably the most easy one is to check if the current Fragment in your container is an instance of FragmentXYZ (in your case MagazineViewFragment).

Example

Fragment mFragment = getFragmentManager().findFragmentById(R.id.container);
if (mFragment instanceof MagazineViewFragment)
    return;
like image 117
reVerse Avatar answered Sep 29 '22 04:09

reVerse