編輯:關於 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……
Android startActivityForResult 詳解:頁面跳轉與數據回傳
一、Activity 之間常見的跳轉方式 在 Android 裡切換畫面最常用的兩種寫法如下: 1)startActivity(Intent intent); 2)sta
Android 消息機制深度解析:Handler、Looper、MessageQueue 源碼全通關
接觸 Android 的第一天就聽說了「消息機制」,但那時候的理解僅止於看看別人的博客、記住幾個類名而已,從未真正深入。最近重新過了一遍消息機制和相關源碼,這裡做個系統
在Mac上使用Android Studio開發JNI的完整教學
對於剛踏入Android開發的新手而言,從環境配置到真正寫出第一行程式碼,JNI的學習路徑往往充滿坎坷。本文把整個流程重新梳理了一遍,希望能幫助同樣在摸索中的開發者少走彎
Android Fragment 實戰:ToDoList 待辦清單詳解
ToDoList(Fragment)詳解 Fragment(碎片)可以靈活地從 Activity 上添加或刪除,能帶來良好的用戶體驗。下面就以一個待辦清單為例,完整走一遍