萬盛學電腦網

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

Android TableLayout 表格佈局詳解:stretch/shrink/collapseColumns 與動態建表

結構層級

TableLayout (根)
  ├─ TableRow
  │   ├─ Cell (View)
  │   └─ Cell (View)
  ├─ TableRow
  │   └─ ...
  └─ 直接子 View (不在 TableRow 中)

關鍵 XML 屬性

屬性說明索引基準
android:stretchColumns指定列延伸填滿剩餘空間第 0 欄為 0
android:shrinkColumns指定列允許壓縮以適應寬度第 0 欄為 0
android:collapseColumns隱藏指定列(可動態切換)第 0 欄為 0

多欄以逗號分隔:android:stretchColumns="0,2"。

XML 靜態表格範例

<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:stretchColumns="0">

    <TableRow>
        <TextView android:text="第一行第一列" android:background="#aa0000" android:padding="3dp"/>
        <TextView android:text="第一行第二列" android:gravity="center_horizontal" android:background="#00aa00" android:padding="3dp"/>
        <TextView android:text="第一行第三列" android:gravity="right" android:background="#0000aa" android:padding="3dp"/>
    </TableRow>

    <TableRow>
        <TextView android:text="第二行第一列" android:padding="3dp"/>
        <TextView android:text="第二行第二列" android:gravity="right" android:padding="3dp"/>
    </TableRow>

    <TextView android:text="獨立於 TableRow 的文字" />
</TableLayout>

動態建表 (Java)

TableLayout table = new TableLayout(this);
table.setStretchAllColumns(true); // 所有欄延伸

for (int r = 0; r < 5; r++) {
    TableRow row = new TableRow(this);
    for (int c = 0; c < 3; c++) {
        TextView tv = new TextView(this);
        tv.setText("R" + r + "C" + c);
        tv.setPadding(10, 10, 10, 10);
        tv.setBackgroundColor((r + c) % 2 == 0 ? 0xFFDDDDDD : 0xFFFFFFFF);
        row.addView(tv);
    }
    table.addView(row);
}
setContentView(table);

動態控制欄位可見性

// 隱藏第 1 欄
table.setColumnCollapsed(1, true);
// 顯示第 1 欄
table.setColumnCollapsed(1, false);

總結

TableLayout 適合規則整齊的表格資料;動態建表時善用 setStretchAllColumns、setColumnCollapsed 靈活控制欄寬與顯隱。複雜表格建議改用 RecyclerView + GridLayoutManager。

copyright © 萬盛學電腦網 all rights reserved