创建线性布局

试试 Compose 方式
Jetpack Compose 是 Android 推荐的 UI 工具包。了解如何在 Compose 中使用布局。

LinearLayout 是一个视图组,它以垂直或水平的单一方向对齐所有子视图。您可以使用 android:orientation 属性指定布局方向。

An image showing a layout split in three vertical slices
图 1. 包含三个水平方向子视图的 LinearLayout

LinearLayout 的所有子视图都堆叠在一起,因此垂直列表每行只有一个子视图,无论其宽度如何。水平列表只有一行高,其高度等于最高的子视图的高度加上内边距。LinearLayout 尊重子视图之间的外边距以及每个子视图的重力(右对齐、居中对齐或左对齐)。

布局权重

LinearLayout 还支持使用 android:layout_weight 属性为单个子视图分配权重。此属性以视图在屏幕上占用的空间量来分配一个“重要性”值。权重值越大,它就可以扩展以填充父视图中剩余的空间。子视图可以指定一个权重值,视图组中任何剩余空间都会根据子视图声明的权重按比例分配给子视图。默认权重为零。

等量分配

要创建线性布局,其中每个子视图在屏幕上使用相同的空间量,请将垂直布局中每个视图的 android:layout_height 设置为 "0dp",或者将水平布局中每个视图的 android:layout_width 设置为 "0dp"。然后将每个视图的 android:layout_weight 设置为 "1"

不等量分配

您还可以创建子元素在屏幕上使用不同空间量的线性布局。请考虑以下示例

  • 假设您有三个文本字段:两个的权重值为 1,第三个的默认权重值为 0。权重值为 0 的第三个文本字段仅占用其内容所需的区域。另外两个权重值为 1 的文本字段则相等地扩展,以填充测量所有三个字段的内容后剩余的空间。
  • 如果改为您有三个文本字段,其中两个的权重值为 1,第三个的权重值为 2,则测量所有三个字段的内容后剩余的空间将按如下方式分配:一半分配给权重值为 2 的字段,另一半平均分配给权重值为 1 的字段。

下图和代码段展示了布局权重在“发送消息”Activity 中的工作方式。收件人字段、主题行和发送按钮都只占用它们所需的高度。消息区域占据了 Activity 的其余高度。

An image showing three EditTexts and a Button in a vertically oriented LinearLayout
图 2. 垂直方向 LinearLayout 中的三个文本字段和一个按钮。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical" >
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/to" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/subject" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="top"
        android:hint="@string/message" />
    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:text="@string/send" />
</LinearLayout>

有关 LinearLayout 的每个子视图可用的属性的详细信息,请参阅 LinearLayout.LayoutParams