You need to enable JavaScript to run this app. 为什么merge布局在LinearLayout中会重复显示两次?
优惠活动
大模型
产品
解决方案
定价
更多

为什么merge布局在LinearLayout中会重复显示两次?

问题原因
  • 父布局中已经通过<include>标签引入了merge子布局,ParentBinding inflate时会自动将merge内的所有元素挂载到父LinearLayout下,生成第一组控件。
  • 后续手动调用ChildBinding.inflate(layoutInflater, binding.root)时,由于子布局根节点是<merge>,inflate操作会直接将merge内的控件再次添加到传入的父容器binding.root中,生成第二组重复控件,也导致了id重复的问题。
修复方案

方案一:保留父布局标签(推荐)

该方案无需单独inflate子布局,通过父绑定直接获取子布局绑定实例:

  1. 给父布局的标签添加唯一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>
  1. 简化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
}

方案二:删除父布局标签

如果需要动态控制子布局挂载时机,可以删掉父布局中的标签,保留手动inflate子布局的逻辑即可。
修改后父布局:

<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 09:15:02