Check if a fragment exists and reuse it

*爱你&永不变心* 提交于 2019-12-23 09:26:43

问题


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?


回答1:


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;



回答2:


Something like this might help:

getFragmentManager().findFragmentById(fragmentId);

Do not forget the null check.




回答3:


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.



来源:https://stackoverflow.com/questions/25567470/check-if-a-fragment-exists-and-reuse-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!