线性布局
LinearLayout
是一种会把所有的子元素排列成一个方向(水平或垂直)的ViewGroup。你可以使用 android:orientation
属性来指定布局的方向。
LinearLayout 的所有子元素都是一个挨着一个排列的,所以对于垂直的列表来说不管子元素有多宽每行只会有一个子元素,水平的列表只会有一行高(最高子节点的高度加上内边距)。LinearLayout
涉及到子元素间的外边距和每个子元素的重心(左、中或右对齐)。
布局比重
相同比重的子元素
把每个子视图的 android:layout_height
设置为"0dp"(对于对平布局)或把每个子视图的 android:layout_width
设置为"0dp"(对于垂直布局),然后把每个视图的 android:layout_weight
设置为"1",这样就能创建一个每个子元素在屏幕上占据相同大小空间的线性布局。
LinearLayout
也支持使用 android:layout_weight
属性为单个的子元素指定比重。视图会依照这个属性指定的值来决定应该占用屏幕多大空间。大的比重值可以使视图扩展来填充父元素视图中所有剩余的空间。子元素视图指定比重值后,ViewGroup中的所有剩余空间会依照他们声明的比例指定给子元素。默认比重值是0。
例如,如果有三个文本框,其中两个的比重值是1,另外一个没有指定比重值,那么没有比重值的文本框只会占用它的内容需要的区域,另外两个会在三个文本被框测量后平均占用剩余的空间。如果第三个文本框的比重被设置为2(而不是0),那么它现在被声明的比其他两个重要了,所以它会拥有总空间的一半,第一和第二个文本框平分剩余的。
事例
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/to" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/subject" />
<EditText
android:layout_width="fill_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.LayoutParams 了解更多关于 LinearLayout 中子元素视图可用属性的细节。