为什么添加视图到我的布局会改变整个布局的宽度?

我添加了一个视图到我的布局的底部添加一个行分隔符在这个元素的末尾。 问题是,在布局中放置此视图后填充整个屏幕的宽度,但是当我把视图,它显示为正确的大小(在我的测试中大约400dp)。 为什么添加的视图会导致布局填满整个屏幕。

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="start" android:orientation="vertical" android:paddingLeft="6dp" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/text_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:textColor="@android:color/darker_gray" android:textSize="12sp" tools:text="Hello, Label" android:paddingBottom="6dp" android:paddingLeft="6dp"/> <TextView android:id="@+id/text_error" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:textColor="@color/sr_red" android:textSize="12sp" tools:text="Error!"/> </LinearLayout> <!-- this View causes the parent layout to fill the whole screen width--> <View android:layout_width="wrap_content" android:layout_height="1dp" android:layout_marginTop="2dp" android:background="@android:color/darker_gray" /> </LinearLayout> 

这是导致问题的最底层。

我正在这样修改视图:

 val inputLayout = createLabelLayout(context, component.name, button) viewGroup.addView(inputLayout.root) inputLayout.setWidth(width) 

这里是相关的类

 private fun <T : View> createLabelLayout(context: Context, text: String, child: T): LabelLayout<T> { val layout = LabelLayout(context, child) layout.label.text = text return layout } private class LabelLayout<out T : View>(context: Context, child: T) { val root = LayoutInflater.from(context).inflate(R.layout.item_custom_field_label, null, false) as ViewGroup val label = root.findViewById(R.id.text_label) as TextView val error = root.findViewById(R.id.text_error) as TextView init { root.addView(child, root.childCount - 1) } fun setWidth(width: Int) { val params = root.layoutParams params.width = width root.layoutParams = params } } 

好的,所以我通过改变LinearLayout的根和LinearLayout的wrap_content来解决了这个问题。 之前我只是改变父布局的宽度。