【问题标题】:Check if a fragment exists and reuse it检查片段是否存在并重用它
【发布时间】:2014-10-23 10:01:45
【问题描述】:

每当用户单击列表视图中的项目时,我都会使用以下代码创建一个片段。 但是通过这种方式,在每次用户点击时都会创建片段。我想要的是重用旧片段(如果存在)并只重新加载其内容(不要创建新片段)。

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

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

我该怎么办?

【问题讨论】:

    标签: java android android-fragments fragment fragmentmanager


    【解决方案1】:

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

    示例

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

    【讨论】:

    • 非常感谢!这就是我要找的东西!
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

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

      getFragmentManager().findFragmentById(fragmentId);
      

      不要忘记空检查。

      【讨论】:

        猜你喜欢
        • 2016-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 2020-08-27
        • 1970-01-01
        相关资源
        最近更新 更多