萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android TableLayout 表格佈局完全指南:屬性、跨列、動態控制實戰

TableLayout 核心屬性

XML 屬性Java 方法作用值格式
android:collapseColumnssetColumnCollapsed(index, true)隱藏指定列(0 基索引,多列逗號分隔)"1,3"
android:shrinkColumnssetColumnShrinkable(index, true)允許列收縮以適應寬度"0,2"
android:stretchColumnssetColumnStretchable(index, true)允許列伸展填滿父容器剩餘空間"*" 或 "1,2"

注意:shrinkColumns 與 stretchColumns 可同時作用同一列,先收縮後伸展,最終填滿父容器寬度。

行列數確定規則

  • 行數 = 直接子視圖數量(通常為 TableRow,也可直接放置 View)。
  • 列數 = 所有行中單元格最大數量。例:Row1 兩個控件,Row2 三個控件 → 表格共 3 列。
  • 列寬由該列最寬單元格決定;表格整體寬度默認 match_parent。

單元格屬性:精確控制佈局

屬性說明示例
android:layout_column指定單元格顯示列索引(0 起),跳過前列留空android:layout_column="2" → 第 3 列
android:layout_span單元格跨列數(默認 1)android:layout_span="3" 佔據 3 列

兩屬性可組合使用,實現複雜佈局(如標題跨列、表單標籤右對齊輸入框左對齊)。

完整示例:計算器風格按鈕面板

<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="*" >  <!-- 所有列均分寬度 -->

    <TableRow>
        <Button android:id="@+id/btn1" android:text="1" android:layout_weight="1" />
        <Button android:id="@+id/btn2" android:text="2" android:layout_weight="1" />
        <Button android:id="@+id/btn3" android:text="3" android:layout_weight="1" />
    </TableRow>

    <TableRow>
        <Button android:id="@+id/btn4" android:text="4" android:layout_weight="1" />
        <Button android:id="@+id/btn5" android:text="5" android:layout_weight="1" />
        <Button android:id="@+id/btn6" android:text="6" android:layout_weight="1" />
    </TableRow>

    <TableRow>
        <Button android:id="@+id/btn7" android:text="7" android:layout_weight="1" />
        <Button android:id="@+id/btn8" android:text="8" android:layout_weight="1" />
        <Button android:id="@+id/btn9" android:text="9" android:layout_weight="1" />
    </TableRow>

    <TableRow>
        <View android:layout_height="2dp" android:background="#FF909090" 
              android:layout_span="3" /> <!-- 分隔線跨 3 列 -->
    </TableRow>

    <TableRow>
        <Button android:id="@+id/btn0" android:text="0" android:layout_span="2" android:layout_weight="1" />
        <Button android:id="@+id/btnDot" android:text="." android:layout_weight="1" />
    </TableRow>
</TableLayout>

動態控制列顯隱

TableLayout table = findViewById(R.id.table);
table.setColumnCollapsed(1, true);  // 隱藏第 2 列
table.setColumnCollapsed(1, false); // 顯示第 2 列
// 運行時動態調整伸縮屬性
table.setColumnStretchable(0, true);
table.setColumnShrinkable(2, true);

適用場景與替代方案

  • 適用:表單、數據報表、計算器面板、固定列數的網格佈局。
  • 不適用:複雜嵌套、需要權重分配不均的彈性佈局 — 改用 GridLayout (API 14+) 或 ConstraintLayout + Guideline / Chain。
copyright © 萬盛學電腦網 all rights reserved