一、概述
线性布局(LinearLayout)是所有Android布局中最简单的一种,它将widget以行或列进行排列。配置LinearLayout有5个重要的属性分别是:填充模式(fill modal)、比重(weight)、排列方式(gravity)、padding。
二、填充模式
填充模式(fill modal) 包括填充指定的像素(例如:125px)、wrap_content、fill_parent.
三、比重(weight)
设置widgets瓜分剩余空间时的比重。以下例子分别演示两个按钮 1:1 和 1:2时的显示情况。
【效果图】
1:1
1:2
【代码要点】
weight12.xml:两个widgets竖直排列,分割剩余空间的比重为1:2时的布局代码.
- <?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:orientation="vertical">
- <Button
- android:id="@+id/widget31"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="weight = 1"
- android:layout_weight="1"
- />
- <Button
- android:id="@+id/widget32"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="weight = 2"
- android:layout_weight="2"
- />
- </LinearLayout>
三、排列方式(gravity)
设置widgets的排列方式,默认为靠左上排列,也可以设置其他的排列方式:靠左、靠右、居中、靠下方等...
当同一行有多个控件时,常用的排列方式为靠下(bottom) 和 竖直居中;
当同一列有多个控件时,常用的排列方式为靠左、居中、靠右;
出来通过在.xml中定义排列方式外,还可以在代码中设置:setGravity().
【效果图】
在水平线性布局下对三个按钮进行靠下方排列。
在竖直线性布局下对三个按钮进行水平居中排列。
【代码要点】
center.xml:竖直线性布局下对三个按钮进行水平居中排列。
- <?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:orientation="vertical">
- <Button
- android:id="@+id/widget31"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="center-1"
- android:layout_gravity="center_horizontal"
- />
- <Button
- android:id="@+id/widget32"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="center-2"
- android:layout_gravity="center_horizontal"
- />
- <Button
- android:id="@+id/widget33"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="center-3"
- android:layout_gravity="center_horizontal"
- />
- </LinearLayout>
四、padding
设置widget控件外沿与内容的边距.
【效果图】
一个按钮填充整个屏幕,设置文字内容与按钮外沿的左边距(paddingLeft)是"90px"
【代码要点】
padding.xml
- <?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">
- <Button
- android:id="@+id/widget31"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:text="padding 10px"
- android:paddingLeft="90px"
- />
- </LinearLayout>