常见界面布局之TableLayout(表格布局)

    技术2025-03-27  36

    1.什么是TableLayout(表格布局)

    TableLayout (表格布局)采用行、列的形式来管理控件,它不需要明确声明包含多少行、多少列,面是通过在TableLayout布局中添加TableRow布局或控件来控制表格的行数,可以在TableRow 布局中添加控件来控制表格的列数。在XML布局文件中定义表格布局的基本语法格式如下:

    <TableLayout xmlns:android-"http://schemas.android.com/apk/res/android" 属性-”属性值"> <TableRow> UI控件 </TableRow> UI控件 </TableLayout>

    TableLayout继承自LinearLayout, 因此它完全支持LinearLayout所支持的属性,此外,它还有其他的常用属性。TableLayout布局的常用属性如表所示。 表 TableLayout 布局的常用属性

    属性名称功能描述android:stretchColumns设置可被拉伸的列。如:android:stretchColumns-~0”, 表示第1列可被拉伸android:shrinkColumns设置可被收缩的列,如:android:shrinkColumns=“1. 2”, 表示2, 3列可收编android:collapseColumns设置可被隐藏的列,如:android:collapseColumns=~0”, 表示第1列可被隐藏

    TableLayout布局中的控件有两个常用属性android:layout_column与jandroid:layout_span, 分别用 于设置控件显示的位置、占据的行数,如表所示。 表 TableLayout 布局中控件的常用属性

    属性名称功能描述android:layout_column设置该控件显示的位置,如 android:layout_column-"l”表示在第2个位置显示android:layout_span设置该控件占据儿行,默认为1行

    在TableLayout(表格布局)中,列的宽度由该列中最宽的那个单元格(控件)决定,整个表格布局的宽度则取决于父容器的宽度。

    创建程序

    创建一个名为TableLayout的应用程序,指定包名为cn.itcast.tablelayout.

    放置界面控件

    在activity_main.xml文件的TableLayout布局中放置3个TableRow布

    局,在TableRow布局中添加不同数量的按钮。

    <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" //设置可被拉伸的列 android:stretchColumns="2" > <TableRow> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" //设置该控件显示的位置 android:layout_column="0" android:text="按钮1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:text="按钮2" /> </TableRow> <TableRow> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:text="按钮3" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="2" android:text="按钮4" /> </TableRow> <TableRow> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="2" android:text="按钮5" /> </TableRow> </TableLayout>

    Processed: 0.011, SQL: 12