我在父级 fragment 线性布局(fragmentContainer)中动态加载一堆子级 fragment ,然后当用户单击按钮时,我需要将它们全部删除并添加新的。我不知道每次会添加多少 fragment 。这是我一次性删除所有 fragment 的方法
LinearLayout ll = (LinearLayout) view.findViewById(R.id.fragmentContainer);
ll.removeAllViews();
现在我可以使用 fragment 事务方法添加新的。 这种删除所有 fragment 的方法非常简单,对我来说比使用remove()逐个删除每个 fragment 更好,但这是一个好的做法吗?性能怎么样?您有更好的方法推荐吗?
最佳答案
This is my way of removing all the fragments at once
不,不是。这是从该容器中删除所有 View 的方法。
This way of removing all fragments is super easy and works for me.
它确实会删除任何 fragment 。它会删除 View 。这就是该方法被命名为 removeAllViews()
的原因。 .
But is it a good practice?
没有。对于初学者来说,当您旋转设备或进行配置更改时,您会注意到所有“删除的” fragment 都会回来。
Do you recommend a better way?
跟踪未完成的 fragment (例如,使用 ArrayList<Fragment>
),然后迭代该列表,将每个 fragment 传递给 remove()
FragmentTransaction
上的方法.
关于android - 删除所有(子) fragment 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30551939/