1、什么是TableLayout
表格布局,以行列的形式管理子控件,每一行为一个TableRow的对象,当然也可以是一个View的对象。TableLayout可以用来实现如计算器之类的布局(但是在更多情况下所使用的是LinearLayout)
2、示例:
这6个Button就是放在TableLayout的TableRow中的。图中的蓝色框框就是一个TableRow。一共两个TableRow,一个TableRow里面放了3个Button。
下面给出布局文件代码:
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3" />
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button4" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button5" />
<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button6" />
</TableRow>
</TableLayout>
3、TableLayout常用属性:
全局属性:
(1)
android:collapseColumns="1,2"
//隐藏从0开始的索引列。列之间必须用逗号隔开,如:1,2
//例如上图中一共有3列控件,当在TableLayout下添加这列代码时
//第2和第3列控件就会被隐藏(因为列数从0开始,所以隐藏的不是第1和第2列)
//如下图
(2)
android:shrinkColumns="2"
//收缩从0开始的索引列。当可收缩的列太宽(内容过多)不会被挤出屏幕.
//列之间必须用逗号隔开:1,2,5,可以通过*代替收缩所有列。
//注意一列能同时表示收缩和拉伸。
//先看图:
假如我把Button3的内容改为“i like android!”
这是添加shrinkColumns属性之前的效果,可以看到由于内容过长,Button的范围已经超出屏幕–>
添加shrinkColumns属性之后,Button3(也就是第3列)被收缩了–>
(3)
android:stretchColumns="1"
//拉伸从0开始的索引列。以填满剩下的多余空白空间。
//列之间必须用逗号隔开:1,2,可以通过*代替拉伸所有列。
//注意一列能同时表示收缩和拉伸。
//还是看图:
这是最开始的时候没有添加任何属性的图–>
再来看看添加了android:stretchColumns=”1” 属性的图–>
可以明显的看到第2列被拉伸了,并且整个TableRow已经被3个控件填满了。
上面3个属性是TableLayout的全局属性,接下来来看看它的子类控件的属性
局部属性:
(1)
android:layout_column="1" //该控件显示在第2列
当在Button1的属性中添加上述语句时,可以看到,Button1会占据TableRow的第2列,后面的控件依次后移
(2)
android:layout_span="2" //该控件占据2列
例如:我在Button1的属性下添加上述语句
可以看到此时Button1会占据2列,而Button2被挤到第3列,Button3则被挤到第4列