删除片段并替换新片段

时间:2018-04-08 21:45:45

标签: android android-fragments

也许主题重复,有很多主题。但我检查了所有这些,但我没有得到解决。

我有一个fragmentFrameLayout上膨胀,当我点击特定的button时,我必须删除当前的一个并将其替换为另一个..但此过程不会工作。首先fragment充气,然后我点击已删除button fragment。但另一个是创造的。它不会出现在屏幕上。虽然调用了onCreateView()方法。

这是我的代码:

Fragment fragment = mFragmentManager.findFragmentById(frameId);

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

2 个答案:

答案 0 :(得分:1)

你在这里做的是:

  1. 从容器中检索FragmentA。
  2. 从容器中删除FragmentA。然后承诺。
  3. 再次使用FragmentA替换空容器的内容(无)。然后承诺。
  4. 我在这里看到两个问题:

    1. 您正在删除Fragment,提交它(因此Fragment现在正在通过生命周期方法onStop(),onDestroy()等),然后您再次尝试添加它(在replace()电话中。您不应该添加已经删除的片段,因为它将被活动销毁。这可能解释了你在屏幕上看到的口吃;新的Fragment在它被销毁之前被添加到容器中。
    2. remove()之前无需replace()replace()remove()容器中的所有片段,然后add()新的片段。
    3. 说明新片段实例化和删除冗余的解决方案:

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

答案 1 :(得分:0)

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

replace的参数也是replace (int containerViewId, Fragment fragment)。从第一行开始,frameId似乎是要替换的片段的id。 frameId应该是包含FrameLayout的ID。