也许主题重复,有很多主题。但我检查了所有这些,但我没有得到解决。
我有一个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();
}
答案 0 :(得分:1)
你在这里做的是:
我在这里看到两个问题:
replace()
电话中。您不应该添加已经删除的片段,因为它将被活动销毁。这可能解释了你在屏幕上看到的口吃;新的Fragment在它被销毁之前被添加到容器中。 remove()
之前无需replace()
。 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();
}
答案 1 :(得分:0)
在尝试更换之前不要删除该片段。
replace
的参数也是replace (int containerViewId, Fragment fragment)
。从第一行开始,frameId
似乎是要替换的片段的id。 frameId
应该是包含FrameLayout
的ID。