Check if a fragment exists and reuse it
Asked Answered
U

3

9

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?

Umbilicus answered 29/8, 2014 at 11:34 Comment(0)
O
17

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;
Oxtail answered 29/8, 2014 at 11:39 Comment(0)
N
1

Add tag when you call your fragment from activity:

FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentByTag( MagazineViewFragment.TAG);
if (fragment == null) {
MagazineViewFragment fragment = new MagazineViewFragment();
fragment.openStream(itemSelected);
getFragmentManager()
.beginTransaction()
.add(R.id.container, fragment, MagazineViewFragment.TAG)
.commit();
}

If you need only to update itemSelected - see broadcasts or listeners.

Nasser answered 29/8, 2014 at 14:47 Comment(0)
B
0

Something like this might help:

getFragmentManager().findFragmentById(fragmentId);

Do not forget the null check.

Baun answered 29/8, 2014 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.