android - 删除所有(子) fragment 的正确方法

标签 android android-fragments android-nested-fragment

我在父级 fragment 线性布局(fragmentContainer)中动态加载一堆子级 fragment ,然后当用户单击按钮时,我需要将它们全部删除并添加新的。我不知道每次会添加多少 fragment 。这是我一次性删除所有 fragment 的方法

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

现在我可以使用 fragment 事务方法添加新的。 这种删除所有 fragment 的方法非常简单,对我来说比使用remove()逐个删除每个 fragment 更好,但这是一个好的做法吗?性能怎么样?您有更好的方法推荐吗?

Child fragments

最佳答案

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/

相关文章:

java - 通用类未找到异常

android - 如何在 actionBar android 中显示 Fragment 中的 DialogFragment

java - 将事件添加到 "Material-Calendar-View"插件的日历时出现问题

android - 为android 4.0实现SIP服务器

android - 无法使用 appcompat 支持库

android - JNI UnsatisfiedLinkError,不兼容 2 个库 : Card. io + OpenTok

android - 在fragment中调用Camera Service,如何处理回调?

android - 无法将多个 fragment 添加到 LinearLayout

android - NoSuchMethodError getChildFragmentManager()

android - 如何使用嵌套 fragment (Android 4.2)在 ViewPager 中添加 fragment