【问题标题】:getFragments method returns only 1 fragment when using replace transactions, used to return allgetFragments 方法在使用替换事务时只返回 1 个片段,用于返回所有
【发布时间】:2017-10-19 10:20:53
【问题描述】:

从 SDK 26.0.0-beta1 及更高版本开始,使用 getFragments https://developer.android.com/reference/android/support/v4/app/FragmentManager.html#getFragments() 方法返回一个只有 1 个片段的列表,并且列表的大小也始终为 1(因此这不包括任何可能的空条目这可能会误导我),当使用replace 方法进行片段导航时。

请记住,我使用的是getSupportFragmentManager,而不是getFragmentManager

在此 SDK 版本之前,所有使用 replace 完成的片段事务都将列在 getFragments 方法中。这意味着如果我替换了 10 个片段,那么 getFragments 将返回一个包含所有这 10 个片段的列表。

但是,从 SDK 26.0.0-beta1 - 特别是 - 及更高版本(26.0.0-alpha1 及更低版本没有此问题),该方法始终返回大小为 1 的列表,其中仅包含被替换的最后一个片段。

为了避免这个问题,我开始使用add 并隐藏之前可见的片段,到目前为止,这符合我的要求,即在需要时检查getFragments 列表中的第一个片段以及查看片段的某个实例是否已经在该列表中。

现在,当我尝试使用共享元素转换时出现了一个新问题,它仅适用于 replace(据我的 google fu 允许我找到),这意味着如果我想使用共享元素转换,我必须返回使用replace 片段而不是add,但我会再次回到最初的问题。

所以现在我陷入了这种困境,希望有人能解决这个问题:

  • 有没有办法解决这个问题?
  • 当我们只使用replace 方法时,getFragments 是否假设只返回 1 个片段,或者这种行为是尚未修复的未记录错误?
  • 是否可以在不使用replace的情况下在片段之间进行共享元素转换?

【问题讨论】:

    标签: android android-studio android-fragments fragmentmanager


    【解决方案1】:

    我知道这是一篇旧帖子,您现在可能已经解决了,但这是我在谷歌搜索相同问题时发现的第一件事,所以希望这可以帮助某人(当我在几个月的时间)。

    如果你调用 fragmentManager.getBackStackEntryCount(),你应该得到你在 backstack 上的所有片段的计数。假设您在添加/替换片段时为片段分配了一个标签,然后将它们添加到后台堆栈,那么您可以在后台堆栈上获取片段的标签并使用 fragmentManager.findFragmentByTag() 获取其实例。

    在片段添加/替换期间设置标签:

    transaction.replace(R.id.fragment_container, newFragment, fragmentName)
    transaction.add(R.id.fragment_container, newFragment, fragmentName)
    

    并将其添加到后台堆栈:

    transaction.addToBackStack(fragmentName);
    

    然后循环遍历你的 backstack 来找到一个特定的片段:

    final FragmentManager fragmentManager = getSupportFragmentManager();
    for (int i = fragmentManager.getBackStackEntryCount() - 1; i >= 0; i--)
    {
        Fragment fragment = fragmentManager.findFragmentByTag(fragmentManager.getBackStackEntryAt(i).getName());
        // ...
    }
    

    我正在反向迭代片段,所以我添加的最后一个片段将首先返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      相关资源
      最近更新 更多