【问题标题】:Confused with android:width=match_parent versus wrap_content与 android:width=match_parent vs wrap_content 混淆
【发布时间】: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 android-layout


【解决方案1】:

做这个。

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/darker_gray">

你会看到“kunal”和“kagure”占据了整个屏幕的宽度 但是“Vip list”和“lyla”得到了它需要的宽度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多