【问题标题】:Remove fragment and replace a new one删除片段并替换一个新片段
【发布时间】:2018-09-18 06:27:50
【问题描述】:

也许主题是重复的,并且有很多关于此的主题。但我检查了所有这些,但我没有得到解决。

我有一个fragment,它在FrameLayout 上膨胀,当我点击特定的button 时,我必须删除当前的一个并用另一个替换它......但是这个过程不起作用。起初fragment 也膨胀了,然后我们点击button 将fragment 删除。但是另一个被创建了。它不会出现在屏幕上。虽然调用了onCreateView()方法。

这是我的代码:

Fragment fragment = mFragmentManager.findFragmentById(frameId);

 if (fragment != null) {
  mFragmentManager.beginTransaction().remove(fragment).commit();
  mFragmentManager.beginTransaction().replace(frameId,fragment).commit();
 }

【问题讨论】:

  • 为什么要删除片段?换个就行了。
  • 我想刷新片段,我尝试使用附加和分离,但我在我的应用程序中遇到了这种技术的问题。如果我直接使用替换,片段不会调用onCreateView() 方法
  • 您在做什么需要您通过删除和重新添加片段来“刷新”片段?无论如何,这可能会产生可见的“闪烁”。
  • 我的片段中有一个对象包含捆绑数据,我从另一个片段更新它,所以我希望在更新它时片段调用 onCreateView() 以用新状态替换以前的状态
  • Mohamed,也许这个帖子的公认答案可能会有所帮助 :: stackoverflow.com/questions/19722979/…

标签: android android-fragments


【解决方案1】:

你在这里做的是:

  1. 从容器中检索 FragmentA。
  2. 从容器中移除 FragmentA。然后承诺。
  3. 再次用 FragmentA 替换空容器中的内容(无)。然后承诺。

我在这里看到两个问题:

  1. 您正在删除 Fragment,提交它(因此 Fragment 现在正在经历生命周期方法 onStop()、onDestroy() 等),然后您尝试再次添加它(在 @987654323 @ 称呼)。你不应该添加已经被移除的 Fragment,因为它会被 Activity 销毁。这可能解释了您在屏幕上看到的口吃;新的 Fragment 在容器被销毁之前被添加到容器中。
  2. 在replace() 之前不需要remove()。 replace() 将 remove() 容器中的所有片段,然后 add() 新的片段。

说明新片段的实例化和移除冗余的解决方案:

Fragment fragment1 = getSupportFragmentManager().findViewById(R.id.fragment_container);
if(fragment1 != null) {
    getSupportFragmentManager().remove(fragment1).commit(); //Unnecessary, as replace() will remove this anyway. Once we call this, we cannot use fragment1 again as its onDestroy() method is called. 
    Fragment fragment2 = new TestFragment();
    //If we use fragment2 here, the fragment is replaced on the screen. If I use fragment1, the fragment disappears (not replaced). 
    getSupportFragmentManager().replace(R.id.fragment_container, fragment2).commit();
}

【讨论】:

  • amm,我尝试为片段创建新实例,但我得到相同的结果,所以我认为问题与片段生命周期无关。另外,如果我直接使用replace 方法,片段将保持原样,无需再次调用片段生命周期,因为我认为这是因为片段实例已经存在
  • 您在哪里创建新实例?我试过你的代码,当 Fragment 被删除时,它就无法再次使用了。我在 clickListener 中创建了一个新实例,它可以工作;片段在屏幕上被替换:gist.github.com/urgentx/8a2fdbbfacddb3afbed07759ddecea78
  • 当我使用新实例并将特定对象传递给它并传递给替换函数时,该对象将在片段内为空!我还是不知道是什么原因,你可以看看这个问题,你会明白我的意思stackoverflow.com/questions/49716330/…
【解决方案2】:

在尝试替换之前不要删除片段。

replace 的参数也是replace (int containerViewId, Fragment fragment)。从第一行看来,frameId 是您要替换的片段的 id。 frameId 应该是您包含 FrameLayout 的 id。

【讨论】:

  • frameId 实际上似乎是正确的。 findFragmentById() 方法接受一个整数资源,该资源标识我们要从中检索片段的容器。
  • 我之前已经替换了它,替换代码在else 声明,但我认为我不需要提及它的代码,因为它对我的问题并不重要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多