【发布时间】:2016-03-10 16:07:56
【问题描述】:
我正在尝试了解 Android 布局的工作原理。如果我制作一个简单的线性布局并添加一些文本字段,并将线性布局的宽度设置为 wrap_content,我在更改文本字段的宽度时发现了一个不寻常的效果。如果 Text Field 的宽度是 wrap_content,那么 Text Field 的大小就是预期的(文本的宽度)。但是,如果我将文本字段的宽度设置为 match_parent,则文本字段的大小将增长为设备屏幕的宽度。我希望 Text View 的大小是文本的宽度,而不是屏幕显示的大小。
也就是说,如果父布局的宽度是wrap_content,而子view的宽度是wrap_content,那么子view的宽度就好像变成了设备屏幕的宽度,即和设置一样父视图的宽度为 match_parent。有人可以解释为什么会发生这种情况,因为这对我来说似乎违反直觉。
这里有一些简单的代码来说明我在说什么。将 Kunal 文本视图的宽度从 wrap_content 更改为 match_parent。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray">
<TextView
android:text="VIP List"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#4CAF50"
android:textSize="24sp" />
<TextView
android:text="Kunal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#4CAF50"
android:textSize="24sp" />
<TextView
android:text="Kagure"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#4CAF50"
android:textSize="24sp" />
<TextView
android:text="Lyla"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#4CAF50"
android:textSize="24sp" />
</LinearLayout>
【问题讨论】:
-
不会发生在我身上。当父级包裹内容并且子级匹配父级或包裹内容时,父级与最宽的子级一样宽。在安卓棉花糖上。也许这取决于android版本?