线性布局(LinearLayout)

LinearLayout是一个View组,包含其中的所有子View,都会按照同一方向排列,垂直或水平方向。你可以用android:orentation属性来指定布局的方向。

LinearLayout中的所有子View会被依次排列,因此垂直列表每行中只有一个子View,而不管行有多宽;水平列表只会有一行(用最高的子View的高度加上填充作为行高)。LinearLayout会关注子View间的边缘,以及每个子View的对齐方式(右对齐、中心对齐或左对齐)。

布局权重

LinearLayout还用android:layout_weight属性来支持给单独的子View分配一个权重。这个属性会给一个View分配一个重要性的值,这个值指定了该View应该占据多大的屏幕空间。较大的权重值会允许该View在它的父View中展开填充剩余的空间。子View可以指定一个权重值,然后View组中剩余的空间会按照被声明的权重所占的比率分配给子View。默认权重值是0.

例如,如果有三个文本域,并且其中的两个声明了权重值是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>

技巧提示:要创建一个每个子View在屏幕上都有相同空间的线性布局,对于垂直布局,要把每个子View的android:layout_height属性值都设置为”0dp”,对于与水平布局,要把每个子View的android:layout_width的属性值都设置为”0dp”。然后把每个子View的android:layout_weight属性值都设置为”1”。

Copyright© 2020-2022 li-xyz 冀ICP备2022001112号-1