删除 ChildFragmentManager 未按预期工作

Remove of the ChildFragmentManager is not working as expected

我有一个包含子 Fragment 的父 Fragment,它显示一些数据。

在某些时候,子片段会广播用户已完成(没有要显示的数据)。此时我想删除这个无用的片段,但不知何故我没有成功。我错过了什么吗?

将片段添加到容器中的方式(效果非常好):

if (swipeFragment == null)
    swipeFragment = new SwipeViewFragment();
if (getActivity() != null) {
    getChildFragmentManager().beginTransaction().add(R.id.jobSearchContainer, swipeFragment, "swipe").commitAllowingStateLoss();
    status = SWIPE;
}

我计划删除它的方式(但它不起作用,这是我尝试过的所有变体):

Fragment swipe = getChildFragmentManager().findFragmentByTag("swipe");
if (swipe == null){
    throw new RuntimeException("Nope");
}
getChildFragmentManager().beginTransaction().remove(swipe).commit();
getChildFragmentManager().beginTransaction().hide(swipe).commit();
getChildFragmentManager().popBackStack();
getFragmentManager().beginTransaction().remove(swipe).commit();

我错过了什么?

谢谢

PS:当我说它不起作用时:我的意思是片段没有被删除,我在 logcat

中没有输出

更新

    Fragment swipe = getChildFragmentManager().findFragmentByTag("swipe");
    if (swipe == null){
        throw new RuntimeException("Nope");
    }
    Log.d("DEBUG", ""+getChildFragmentManager().getFragments().size());
    getChildFragmentManager().beginTransaction().remove(swipe).commit();
    getChildFragmentManager().popBackStack();
    Log.d("DEBUG", ""+getChildFragmentManager().getFragments().size());

有一个结果:

1
1

试试这个:

Fragment swipe = getChildFragmentManager().findFragmentByTag("swipe");
if (swipe == null){
    throw new RuntimeException("Nope");
}

getChildFragmentManager().beginTransaction().remove(swipe).commit();
getChildFragmentManager().popBackStack();

Reference

我调试了它,我终于找到了它的全部内容,很抱歉它与我发布的代码无关。不过还是很有意思的!

问题出在视图的 onCreateView 中:

以前是这样的:

View v = inflater.inflate(R.layout.swipe_layout, container);
// Bla bla
return null;

这是个问题,因为我认为该片段然后以某种方式与视图无关...但它工作得很好,因为视图使用容器并且一切都很好

改为使用:

View v = inflater.inflate(R.layout.swipe_layout, container, false);
// Bla bla
return v;

如果你这样做,一切都很好!

我检测到这个问题是因为我试图使视图透明并且我调用了 Fragment.getView() 返回了 null。

那是一个令人讨厌的人。谢谢你们的帮助!