TableLayout 是 Android 中用于创建表格布局的一种布局管理器。它允许你在屏幕上创建表格形式的布局,其中包含多行和多列。每个单元格可以包含一个或多个视图。以下是 TableLayout 的基本属性和使用方法:

基本属性:

  •  android:layout_width 和 android:layout_height: 定义 TableLayout 的宽度和高度。


  •  android:stretchColumns: 定义哪些列将被拉伸以填充剩余的空间。


子元素属性:

  •  android:layout_column: 指定视图所在的列索引(从0开始)。


  •  android:layout_span: 指定视图横跨的列数。


示例代码:

以下是一个简单的 TableLayout 示例:
<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 第一行 -->
    <TableRow>
        <TextView
            android:text="Name"
            android:layout_column="0"
            android:padding="8dp" />
        <TextView
            android:text="Age"
            android:layout_column="1"
            android:padding="8dp" />
        <TextView
            android:text="Gender"
            android:layout_column="2"
            android:padding="8dp" />
    </TableRow>

    <!-- 第二行 -->
    <TableRow>
        <TextView
            android:text="John"
            android:layout_column="0"
            android:padding="8dp" />
        <TextView
            android:text="25"
            android:layout_column="1"
            android:padding="8dp" />
        <TextView
            android:text="Male"
            android:layout_column="2"
            android:padding="8dp" />
    </TableRow>

    <!-- 第三行 -->
    <TableRow>
        <TextView
            android:text="Jane"
            android:layout_column="0"
            android:padding="8dp" />
        <TextView
            android:text="30"
            android:layout_column="1"
            android:padding="8dp" />
        <TextView
            android:text="Female"
            android:layout_column="2"
            android:padding="8dp" />
    </TableRow>

</TableLayout>

在这个示例中,TableLayout 包含了三行,每行包含了三个 TextView,形成一个简单的表格。每个 TableRow 代表表格中的一行,而每个 TextView 代表一个单元格。

注意事项:

  •  TableLayout 是一个相对简单的布局,适用于需要表格形式的数据展示的情况。

  •  对于更复杂的表格布局,可以考虑使用 GridLayout。

  •  TableLayout 的 stretchColumns 属性可以指定在水平方向上拉伸的列,以便均匀填充水平空间。


了解如何使用 TableLayout 对于显示表格形式的数据非常有帮助,它是 Android 布局中的一种常见布局管理器。


转载请注明出处:http://www.pingtaimeng.com/article/detail/15125/Android