Check if the fragment and its reuse exist.

I use the following code to create a snippet every time a user clicks on an item in a list. But in this way, a fragment is created each time the user clicks. I want to reuse the old fragment (if it exists) and only reload its contents (do not 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 this?

+6
source share
3 answers

There are several ways, perhaps the easiest, is to check if the current fragment in your container instance of FragmentXYZ (in your case, MagazineViewFragment ).

Example

 Fragment mFragment = getFragmentManager().findFragmentById(R.id.container); if (mFragment instanceof MagazineViewFragment) return; 
+14
source

Something like this might help:

 getFragmentManager().findFragmentById(fragmentId); 

Do not forget the zero check.

0
source

Add a tag when you call your fragment from an action:

 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 only need to update itemSelected - see broadcasts or listeners.

0
source

Source: https://habr.com/ru/post/974543/


All Articles