也许主题是重复的,并且有很多关于这个的主题。但是我检查了所有这些,但我没有得到解决方案。
我有一个fragment
在FrameLayout
上膨胀,当我单击特定button
时,我必须删除当前的一个并用另一个替换它..但是此过程不起作用。起初,fragment
也膨胀了,然后我们点击了删除fragment
button
。但是创建了另一个。它不会出现在屏幕上。尽管调用了onCreateView()
方法。
这是我的代码:
Fragment fragment = mFragmentManager.findFragmentById(frameId);
if (fragment != null) {
mFragmentManager.beginTransaction().remove(fragment).commit();
mFragmentManager.beginTransaction().replace(frameId,fragment).commit();
}
你在这里做的是:
- 从容器中检索片段 A。
- 从其容器中删除片段 A。然后提交。
- 再次将空容器的内容(无)替换为 FragmentA。然后提交。
我在这里看到两个问题:
- 您正在删除片段,提交它(因此片段现在正在经历生命周期方法onStop(),onDestroy()等),然后您尝试再次添加它(在
replace()
调用中)。您不应添加已删除的片段,因为它将被活动销毁。这可能解释了您在屏幕上看到的口吃;新片段会在容器被销毁之前添加到容器中。 - 在
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();
}
在尝试替换片段之前,不要删除它。
此外,replace
的参数也很replace (int containerViewId, Fragment fragment)
.从第一行来看,frameId
似乎是您要替换的片段的 id。frameId
应该是包含FrameLayout
的 ID。