TableLayout (根)
├─ TableRow
│ ├─ Cell (View)
│ └─ Cell (View)
├─ TableRow
│ └─ ...
└─ 直接子 View (不在 TableRow 中)
| 屬性 | 說明 | 索引基準 |
|---|---|---|
| android:stretchColumns | 指定列延伸填滿剩餘空間 | 第 0 欄為 0 |
| android:shrinkColumns | 指定列允許壓縮以適應寬度 | 第 0 欄為 0 |
| android:collapseColumns | 隱藏指定列(可動態切換) | 第 0 欄為 0 |
多欄以逗號分隔:android:stretchColumns="0,2"。
<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>
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。