作者:刘昊昱
博客:http://blog.csdn.net/liuhaoyutz
表格布局与常见的表格类似,以行、列的形式来管理放入其中的UI组件,表格布局使用<TableLayout>标记定义,在表格布局中,可以添加多个<TableRow>标记,每个<TableRow>标记占用一行。由于<TableRow>标记也是容器,所以还可以在其中放入其它UI组件,每放入一个组件,表格就会增加一列。在表格布局中,列可以被隐藏,也可以被设置为伸展,从而填充可利用的屏幕空间,还可以设置为强制收缩,直到表格匹配屏幕大小。
特别的,如果在表格布局中,直接向<TableLayout>中放入一个UI组件,那么该组件将独占一行。
下面介绍几个TableLayout特有的XML属性:
android:collapseColumns
设置需要被隐藏的列的序号,序号从0开始,多个列序号之间用逗号分隔。
android:shrinkColumns
设置允许被收缩的列的序号,序号从0开始,多个列序号之间用逗号分隔。
android:stretchColumns
设置允许被拉伸的列的序号,序号从0开始,多个列序号之间用逗号分隔。
下面我们来看一个例子,该程序运行效果如下图所示:
主布局文件main.xml内容如下:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="@+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_vertical"
android:stretchColumns="0,3"
>
<!-- 第一行 -->
<TableRow android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView/>
<TextView android:text="用户名:"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:textSize="24px"
android:layout_height="wrap_content"
/>
<EditText android:id="@+id/editText1"
android:textSize="24px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:minWidth="200px"/>
<TextView />
</TableRow>
<!-- 第二行 -->
<TableRow android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView/>
<TextView android:text="密 码:"
android:id="@+id/textView2"
android:textSize="24px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="24px"
android:id="@+id/editText2"
android:inputType="textPassword"/>
<TextView />
</TableRow>
<!-- 第3行 -->
<TableRow android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView/>
<Button android:text="登录"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button android:text="退出"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView />
</TableRow>
</TableLayout>
该程序使用TableLayout,并设置属性android:stretchColumns="0,3",即第1和第4列是可拉伸的,这样做是为了让UI组件显示中屏幕中间位置。
在TableLayout中加入了3个TableRow,即分为3行,每个TableRow中加入了4个UI组件,即4列,注意每行的第1和第4列是内容为空的TextView组件,其作用是为了拉伸填充空间,让第2和第3列显示在屏幕中间。