检查一个片段是否存在并重新使用它[英] Check if a fragment exists and reuse it

本文是小编为大家收集整理的关于检查一个片段是否存在并重新使用它的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

每次用户单击列表视图中的项目时,我都会使用以下代码来创建片段. 但是这样,在每个用户单击时都会创建片段.我想要的是重复使用旧片段(如果存在),只重新加载其内容(不要创建新的内容).

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

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

我该怎么办?

推荐答案

有多种方法,可能最简单的方法是检查container中的当前片段是否是FragmentXyz的实例(在您的情况下MagazineViewFragment).

示例

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

其他推荐答案

从活动中调用片段时添加标签:

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();
}

如果您只需要更新项目选择 - 请参阅广播或侦听器.

其他推荐答案

类似的东西可能会有所帮助:

getFragmentManager().findFragmentById(fragmentId);

不要忘记零检查.

本文地址:https://www.itbaoku.cn/post/2091060.html

问题描述

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?

推荐答案

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;

其他推荐答案

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.

其他推荐答案

Something like this might help:

getFragmentManager().findFragmentById(fragmentId);

Do not forget the null check.