【发布时间】:2021-09-10 23:22:30
【问题描述】:
我有一个 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() 方法在此侦听器上使用时有效,但在代码中的其他点调用时无效?
【问题讨论】:
标签: java android android-fragments