首页 > 解决方案 > 为什么我的合并布局在 LinearLayout 中出现两次?

问题描述

我在父 LinearLayout 中有一个合并布局。出于某种原因,当我运行我的应用程序时,合并布局在片段中显示了两次,一个在另一个之上。Layout Inspector 显示合并布局中在第一组下方重复的所有元素,并且都直接在 LinearLayout 下方。更奇怪的是,重复的元素具有相同的 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 layout="@layout/child_layout" />
</LinearLayout>

子布局:

<merge
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="title" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="stuff" />
    <Button
        android:id="@+id/positiveButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/negativeButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</merge>

片段代码:

    private var _binding: ParentBinding? = null
    private val binding get() = _binding!!

    private var _contentBinding: ChildBinding? = null
    private val contentBinding get() = _contentBinding!!

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = ParentBinding.inflate(layoutInflater)
        _contentBinding = ChildBinding.inflate(layoutInflater, binding.root)
        return binding.root
    }

标签: androidandroid-layout

解决方案


发生了什么?

您在onCreateView.

解决方案

替换这个:_contentBinding = ChildBinding.inflate(layoutInflater, binding.root)

有了这个:_contentBinding = ChildBinding.bind(binding.root)


推荐阅读