Correct way to remove all (Child) fragments

大憨熊 提交于 2019-12-04 11:39:58

This is my way of removing all the fragments at once

No, it isn't. It is your way of removing all views from that container.

This way of removing all fragments is super easy and works for me.

It does remove any fragments. It removes views. That is why the method is named removeAllViews().

But is it a good practice?

No. For starters, when you rotate your device or undergo a configuration change, you will notice that all your "removed" fragments come back.

Do you recommend a better way?

Keep track of the outstanding fragments (e.g., using an ArrayList<Fragment>), then iterate over that list, passing each to a remove() method on a FragmentTransaction.

If you simply want to remove all fragments, code below:

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {    
    fm.popBackStack();
}

This code is good only if you use the add method of FragmentTransaction when referencing fragments. Method popBackStack is used for removing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!