创建线性布局

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

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

一张图片,显示布局拆分为三个垂直切片的图片
图 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。

下图和代码段展示了布局权重如何在“send message”activity 中发挥作用。To 字段、Subject 行和 Send 按钮均仅占用各自所需的高度。消息区域占据 activity 的其余部分高度。

一张图片,显示垂直 LinearLayout 中的三个 EditText 和一个 Button
图 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