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

Android 布局實戰:在 TabHost 中靈活安排 FrameLayout 內容區

編輯:關於 Android 程式設計

TabHost 是早期 Android 做分頁切換的經典元件。它有一個很實用的特性:以 TabHost 為根的布局檔裡,可以同時存在 FrameLayout 形式的內容容器與自訂的頂部/底部區域,自由度比想像中高。

布局檔

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/tab_top"
            android:background="@color/red"
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="20dp"
            android:layout_alignParentTop="true" >
        </LinearLayout>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:background="@color/green"
            android:layout_height="wrap_content"
            android:layout_above="@id/tabs"
            android:layout_below="@id/tab_top" >
        </FrameLayout>

        <TabWidget
            android:id="@+id/tabs"
            android:layout_width="fill_parent"
            android:background="@color/blue"
            android:layout_height="20dp"
            android:layout_alignParentBottom="true" >
        </TabWidget>

    </RelativeLayout>
</TabHost>

結構說明

這個布局由上而下分成三塊,用 RelativeLayout 做定位:

  • 頂部 LinearLayout(tab_top):對齊父容器頂端,可以放標題或自訂的橫向選單。
  • 中間 FrameLayout(tabcontent):內容區,透過 layout_below 與 layout_above 同時夾住上下兩塊,自動填滿剩餘空間。
  • 底部 TabWidget(tabs):對齊父容器底端,負責繪製分頁標籤。

兩個必須注意的 ID

TabHost 之所以能運作,是因為它會去尋找兩個約定好的 ID:

  • @android:id/tabs 對應 TabWidget,用來放各分頁的標籤。
  • @android:id/tabcontent 對應 FrameLayout,用來裝各分頁的實際內容。

這兩個 ID 是寫死在框架裡的,必須原封不動地使用 android: 命名空間下的資源,不能自取名字。上述布局中 TabWidget 寫成 @+id/tabs 之所以仍能運作,是因為 TabHost 在 setup 時會以字串比對,但為了避免版本差異帶來的問題,建議還是統一寫成 @android:id/tabs。

程式碼中的標準三步驟是:取得 TabHost → 呼叫 setup() → 用 addTab() 逐一加入分頁,每個分頁透過 TabSpec 指定標籤與要放進內容區的 Intent。

該用 TabHost 嗎

坦白說,TabHost 早已被標記為 deprecated。新專案請改用 TabLayout 搭配 ViewPager2,或是以 BottomNavigationView 實作底部導覽。TabHost 的價值在於維護老專案時能看懂它的 ID 約定與 TabSpec 模型。

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