线性布局(LinearLayout)是Android五种布局中最简单的布局之一,它提供了控件水平或垂直排列的模型。同时,使用此布局时可以通过设置控件的weight参数来控制各个控件在容器内的相对大小。
LinearLayout布局的属性既可以在布局文件(XML)中设置,也可以通过成员方法进行设置。下面给出LinearLayout常用的属性及其对应属性设置的方法。
属性名称 | 对应方法 | 描述 |
android:orientation | setOrientation(int) | 设置线性布局的朝向,可取horizontal(水平)和vertical(垂直)两种排列方式 |
android:gravity | setGravity(int) | 设置线性布局的内部元素的布局对齐方式 |
线性布局中使用gravity属性来设置其内部子控件的对齐方式,当要为gravity设置多个值时,用“|”来分隔。gravity可取得值及其说明见下表:
属性值 | 说明 |
top | 不改变控件大小,对齐到容器顶部 |
bottom | 不改变控件大小,对齐到容器底部 |
left | 不改变控件大小,对齐到容器左侧 |
right | 不改变控件大小,对齐到容器右侧 |
center_vertical | 不改变控件大小,对齐到容器纵向中央位置 |
center_horizontal | 不改变控件大小,对齐到容器横向中央位置 |
center | 不改变控件大小,对齐到容器中央位置 |
fill_vertical | 若有可能,纵向拉伸以填满容器 |
fill_horizontal | 若有可能,横向拉伸以填满容器 |
fill | 若有可能,纵向横向同时拉伸以填满容器 |
下面来看一下效果:
其中Main.xml代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:gravity="center_horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <LinearLayout android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="2">
- <TextView android:text="Welcome to sunchis.com"
- android:textSize="15pt"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
- <LinearLayout android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="1">
- <!-- 这里字水平居中 -->
- <TextView android:text="red"
- android:gravity="center_horizontal"
- android:background="#aa0000"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- <TextView android:text="green"
- android:gravity="center_horizontal"
- android:background="#00aa00"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- </LinearLayout>
- </LinearLayout>