我有一个 FrameLayout,它可以根据用户在 RadioGroup 上的选择填充不同的片段。然而,我很确定我用来去除这些碎片的方法远非理想,如果可能的话,我想了解如何正确地做到这一点。
我现在如何删除碎片:
(...)
//Inside the body of the OnViewCreated
FragmentManager manager = getChildFragmentManager();
//RadioGroup listener to show a fragment based on the user's choice
radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
//getCheckedRadio is only a method I created to get the index of the option chosen by the user
int index = getCheckedRadio(group);
switch (index) {
case 1:
getChildFragmentManager().beginTransaction().replace(R.id.child_fragment, new FragmentA()).commit();
break;
case 2:
getChildFragmentManager().beginTransaction().replace(R.id.child_fragment, new FragmentB()).commit();
break;
case 3:
getChildFragmentManager().beginTransaction().replace(R.id.child_fragment, new FragmentC()).commit();
break;
default:
removeFragments();
break;
}
(...)
//Method I use to remove the fragments
public void removeFragments() {
try {
FragmentA fragA = (FragmentA) manager.findFragmentById(R.id.child_fragment);
if (fragA != null)
manager.beginTransaction().remove(fragA).commit();
} catch (Exception e) {
try {
FragmentB fragB = (FragmentB) manager.findFragmentById(R.id.child_fragment);
if (fragB != null)
manager.beginTransaction().remove(fragB).commit();
} catch (Exception f) {
try {
FragmentC fragC = (FragmentC) manager.findFragmentById(R.id.child_fragment);
if (fragC != null)
manager.beginTransaction().remove(fragC).commit();
} catch (Exception g) {
Toast.makeText(getContext(), "Try Again", Toast.LENGTH_SHORT).show();
}
}
}
}
但是,我知道这种方法远非完美,因为如果我在 之外的任何时候调用它radioGroup.SetOnCheckedChangeListener,它不会删除当时暴露的片段。所以我的问题是:从可以容纳不同类型片段的 FrameLayout 中删除片段的正确方法是什么?为什么我的removeFragments()方法在此侦听器上使用时有效,但在代码中的其他点调用时无效?