LinearLayout
LinearLayout是所有的子控件在一个方向,垂直或水平的父组件。你可以指定使用android:orientation设置布局的方向。
LinearLayout所有的子控件一个接一个,所以一个垂直列表的话,每行只有一个孩子,无论他们有多宽,一个水平列表只会有一行高(最高的孩子的身高,加上填充)。LinearLayout关心每个子控件与其他设置了gravity(右、中心或左对齐)属性之间之间的margin值。
Layout Weight
LinearLayout还支持使用android:layout_weight属性分配个个个体(子控件)的比重。这个属性分配一个“重要”的值对于一个控件在屏幕上应该占多少空间。在父视图中更大的比重值使其扩大剩余的可用于填补的空间。子视图可以指定一个权重值,然后剩余的空间将按照声明的比例被分配给子控件。默认的weight值为零。
例如,如果有三个文本字段和他们两个声明1的比重,而另一个没有比重,没有比重的第三个文本字段是不会向外扩展,只会占据其内容所需的区域。其他两个将扩大同样填补剩下的空间毕竟测量三个字段。如果第三个控件是给定一个比重为2(而不是0),然后现在声明比其他的更重要,所以它将占有一半的总剩余空间,而前两个分享剩余的空间。
Example
<?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>
Tips:同样比重的子控件
创建一个线性布局,每个孩子在屏幕上使用相同数量的空间,设置android:layout_height每个视图的“0dp”(垂直布局)或android:layout_width每个视图的“0dp”(水平布局)。然后将android:layout_weight每个视图的“1”。
——–意思就是在使用android:layout_weight属性时,请把android:layout_height或者android:layout_width设置为0dp