Correct way to remove all (Child) fragments

ThanosFisherman picture ThanosFisherman · May 31, 2015 · Viewed 10.3k times · Source

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?

Child fragments

Answer

CommonsWare picture CommonsWare · May 31, 2015

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.