Android官方文档—User Interface(Layouts)(Linear Layout)

Linear Layout

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

LinearLayout的所有子项一个接一个地堆叠,因此垂直列表每行只有一个子节点,无论它们有多宽,水平列表只有一行高(最高子节点的高度,加上填充)。 LinearLayout尊重子项与每个子项的重力(右,中或左对齐)之间的边距。

布局比权重


LinearLayout还支持使用android:layout_weight属性为各个子项分配权重。此属性根据应在屏幕上占用的空间为视图指定“重要性”值。较大的权重值允许它扩展以填充父视图中的任何剩余空间。子视图可以指定权重值,然后视图组中的任何剩余空间将按其声明的权重比例分配给子项。默认权重为零。

例如,如果有三个文本字段,其中两个声明权重为1,而另一个没有权重,则没有权重的第三个文本字段不会增长,只会占用其内容所需的区域。在测量所有三个场之后,另外两个将平均扩展以填充剩余的空间。如果第三个字段的权重为2(而不是0),则现在宣布它比其他字段更重要,因此它获得剩余空间总量的一半,而前两个平均分配其余部分。

同等权重

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

示例


<?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="right"
        android:text="@string/send" />
</LinearLayout>

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

猜你喜欢

转载自blog.csdn.net/weixin_42703445/article/details/83753272
今日推荐