为什么merge布局在LinearLayout中会重复显示两次?
问题原因
- 父布局中已经通过
<include>标签引入了merge子布局,ParentBindinginflate时会自动将merge内的所有元素挂载到父LinearLayout下,生成第一组控件。 - 后续手动调用
ChildBinding.inflate(layoutInflater, binding.root)时,由于子布局根节点是<merge>,inflate操作会直接将merge内的控件再次添加到传入的父容器binding.root中,生成第二组重复控件,也导致了id重复的问题。
修复方案
方案一:保留父布局标签(推荐)
该方案无需单独inflate子布局,通过父绑定直接获取子布局绑定实例:
- 给父布局的
标签添加唯一id:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <include android:id="@+id/childContent" layout="@layout/child_layout" /> </LinearLayout>
- 简化Fragment代码,删除子布局单独inflate逻辑:
private var _binding: ParentBinding? = null private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = ParentBinding.inflate(layoutInflater) // 子布局控件直接通过binding.childContent访问,例如 binding.childContent.positiveButton return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null }
方案二:删除父布局标签
如果需要动态控制子布局挂载时机,可以删掉父布局中的
修改后父布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> </LinearLayout>
Fragment代码无需修改,同时补充绑定实例的置空逻辑避免内存泄漏:
override fun onDestroyView() { super.onDestroyView() _contentBinding = null _binding = null }
内容的提问来源于stack exchange,提问作者notReallyDev
相关产品推荐
相关产品推荐

