Correct way to remove all (Child) fragments

只愿长相守 提交于 2020-01-01 17:09:08

问题


I load a bunch of Child fragments dynamically inside a Parent's Fragment linearLayout (fragmentContainer), then when user clicks a button, I need to remove them all and add new ones. I don't know the exact number of fragments that will be added each time. This is my way of removing all the fragments at once

LinearLayout ll = (LinearLayout) view.findViewById(R.id.fragmentContainer);
ll.removeAllViews();

Now I can add the new ones using fragment transaction methods. This way of removing all fragments is super easy and works for me better than removing each fragment one by one using remove() But is it a good practice? How about performance? Do you recommend a better way?


回答1:


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.




回答2:


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.




回答3:


In Kotlin you can do:

repeat(fragmentManager.backStackEntryCount) {
    fragmentManager.popBackStack()
}

Where fragmentManager could be one of:

  • Activity.supportFragmentManager
  • Fragment.childFragmentManager
  • Fragment.requireActivity().supportFragmentManager
  • Fragment.requireFragmentManager()


来源:https://stackoverflow.com/questions/30551939/correct-way-to-remove-all-child-fragments

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