第一节介绍了新建Android项目时默认生成的布局文件,默认的布局文件采用的相对布局RelativeLayout,在这个布局中也默认添加了一个TextView控件。本节讲的这个LinearLayout线性布局和RelativeLayout相对布局类似,同属于布局容器,也可以包裹普通UI控件(TextView、Button等)。
线性布局是按照水平或垂直的方式将布局元素(控件或布局)按照顺序依次排列,后面的元素将位于前面元素的下方或右方。至于是下方或右方,和布局设置的方向有关,可以通过设置属性orientation的值为horizontal(水平)或vertical(垂直)来实现。
3.3.1 LinearLayout基础用法
下面通过一个实例来看一下orientation属性值为vertical时的效果:
<?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:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30sp" />
</LinearLayout>
添加了一个LinearLayout布局容器并设置其orientation属性值为vertical,按照上面的解释,所有的子控件都应该垂直排列,通过Android Studio的预览功能来看一下效果,如图3.15所示。