学完了线性布局以及相对布局,再看一种比较常见的TableLayout表格布局,当然Android的布局还有帧布局FrameLayout以及绝对布局AbsoluteLayout因为用的比较少,所以不会再讨论,如果有兴趣的可以自己谷歌。
TableLayout允许我们使用表格的方式来排列控件,每一行是一个TableRow对象,或一个普通控件。当为TableRow对象时,可在TableRow下添加子控件,默认情况下,每个子控件占据一列。当为普通控件时,该控件将独占一行。
TableLayout的行数由有多少个TableRow对象(或View控件),就有多少行。TableLayout的列数等于含有最多子控件的TableRow的列数。如第一TableRow含2个子控件,第二个TableRow含3个,第三个TableRow含4个,那么该TableLayout的列数为4.
以下介绍下表格布局的一些常见的属性下,可以参考TableLayout表格布局详解
1、全局属性也即列属性,有以下3个参数:
android:stretchColumns //设置可伸展的列。该列可以向行方向伸展,最多可占据一整行。
android:shrinkColumns //设置可收缩的列。当该列子控件的内容太多,已经挤满所在行,那么该子控件的内容将往列方向显示。
android:collapseColumns //设置要隐藏的列。
示例:
android:stretchColumns="0" 第0列可伸展
android:shrinkColumns="1,2" 第1,2列皆可收缩
android:collapseColumns="*" 隐藏所有行
- 1
- 2
- 3
- 4
- 5
- 6
- 7
2单元格属性,有以下2个参数:
android:layout_column 指定该单元格在第几列显示
android:layout_span 指定该单元格占据的列数(未指定时,为1)
示例:
android:layout_column="1" 该控件显示在第1列
android:layout_span="2" 该控件占据2列
说明:一个控件也可以同时具备这两个特性。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
同样,我们以之前介绍下使用表格布局实现之前实现过的一个例子:
这个看是需要3TableRow完成,然后第1和第2个TableRow里面应该有2个控件,所以这个表格布局是有3行2列的,第3行显示的时候应该是要跨两列显示的,所以需要设置android:layout_span="2"
,另外,需要设置第2列可以伸展显示这样才可以将输入框铺满屏幕宽度,即设置android:shrinkColumns="1"
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
//设置第2列可以伸展显示
android:stretchColumns ="1">
<TableRow>
<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"/>
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="TextView1"
android:singleLine="true"/>
</TableRow>
<TableRow>
<Button
android:id="@+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/bt1"
android:text="Button2"/>
<EditText
android:id="@+id/et2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="TextView2"
android:singleLine="true"/>
</TableRow>
<TableRow>
<Button
android:id="@+id/login"
android:layout_height="wrap_content"
//跨两列显示
android:layout_span="2"
android:text="login" />
</TableRow>
</TableLayout>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45