java 检查片段是否存在并重用它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25567470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:14:23  来源:igfitidea点击:

Check if a fragment exists and reuse it

javaandroidandroid-fragmentsfragmentfragmentmanager

提问by Usi Usi

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?

我能怎么做?

回答by reVerse

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

有多种方法,可能最简单的方法是检查您当前的 Fragment 是否是 FragmentXYZcontainer的实例(在您的情况下MagazineViewFragment)。

Example

例子

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

回答by Thomas R.

Something like this might help:

像这样的事情可能会有所帮助:

getFragmentManager().findFragmentById(fragmentId);

Do not forget the null check.

不要忘记空检查。

回答by QArea

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.

如果您只需要更新 itemSelected - 请参阅广播或侦听器。