Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 表格佈局 TableLayout 詳解

編輯:關於 Android 程式設計

TableLayout(表格佈局)以「列」與「行」的方式來管理 UI 元件。它不需要事先宣告包含幾行幾列,而是透過 TableRow 及其他元件自動推算出表格的行列數。

運作規則如下:

TableRow 本身也是容器,可以在裡面加入其他元件;每加入一個元件,該表格就增加一列。

若直接把元件放進 TableLayout(而非包在 TableRow 裡),該元件會獨佔一整行。

在表格佈局中,每一列的寬度由該列最寬的儲存格決定;整個 TableLayout 的寬度則取決於父容器(預設填滿父容器)。

由於 TableLayout 繼承自 LinearLayout,因此完全支援 LinearLayout 的所有 XML 屬性,此外它還提供以下專屬屬性:

1. android:collapseColumns / setColumnCollapsed(int, boolean):設定要隱藏的列的序號,多個以逗號分隔。

2. android:shrinkColumns / setShrinkAllColumns(boolean):設定允許被收縮的列的序號,多個以逗號分隔。

3. android:stretchColumns / setStretchAllColumns(boolean):設定允許被拉伸的列的序號,多個以逗號分隔。

以下程式碼示範了 TableRow 的使用、未使用 TableRow 的差異,並讓第二列可收縮、第三列可拉伸:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
      >
  <!-- 定義第一個表格布局,指定第二列允許收縮,第三列允許拉伸 -->
  <TableLayout
 android:id="@+id/tablelayout1"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:shrinkColumns="1"
 android:stretchColumns="2"
 >
 <!-- 直接添加一個button,他自己會占用一行 -->
 <Button
android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="獨自占用一行的按鈕"/>
 <!-- 先添加一個tableRow,在添加三個button, 結果應該是三個button在這個tableRow(行)裡面,即排列為一行 -->
 <TableRow >
 <Button android:layout_width="wrap_content"
 android:layout_height="wrap_content"
android:text="RBtn1"/>
 <Button
 android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RBtn2"/>
 <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
 android:text="RBtn3"/>
</TableRow>
 </TableLayout>
 </LinearLayout>

若要隱藏某一列,可在 TableLayout 中加入如下屬性:

android:collapseColumns="0"

特別提醒:設定列號時是從 0、1、2、3…… 開始計算,而不是 1、2、3……

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved