Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android TabHost 標籤頁控件詳解:從布局到程式碼實作

編輯:Android 開發實例

TabHost 是 Android 中用來實作標籤頁(Tab)切換的容器控件,能讓使用者在多個頁面之間快速切換。以下從原理、關鍵方法到完整範例逐步說明。

一、概述

TabHost 提供了一個專用的窗口視圖容器,內部包含兩個子元素:一組是讓使用者點選的標籤按鈕,另一組則是用來承載各分頁內容的 FrameLayout。需要注意的是,個別分頁的設定通常透過 TabHost 這個容器物件來控制,而不是直接設在子檢視上。

二、重要方法

  • addTab(TabHost.TabSpec tabSpec):新增一個標籤頁。
  • clearAllTabs():清除所有已關聯的標籤頁。
  • getCurrentTab():取得目前所在的分頁索引。
  • getTabContentView():取得承載內容的 FrameLayout。
  • newTabSpec(String tag):建立一個新的 TabSpec 並關聯標記。

三、實作範例

1. 布局檔(以 FrameLayout 作為內容容器)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView android:id="@+id/view1"
        android:background="@drawable/b"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="頁1" />

    <TextView android:id="@+id/view2"
        android:background="@drawable/c"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="頁2" />

    <TextView android:id="@+id/view3"
        android:background="@drawable/d"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="頁3" />

</FrameLayout>

2. 讓 Activity 繼承 TabActivity

public class TabHostDemo extends TabActivity {

3. 取得 TabHost 實例

TabHost tabHost = getTabHost();

4. 設定布局

LayoutInflater.from(this)
        .inflate(R.layout.tabhostpage, tabHost.getTabContentView(), true);

5. 加入各分頁

tabHost.addTab(tabHost.newTabSpec("tab1")
        .setIndicator("分頁一")
        .setContent(R.id.view1));

tabHost.addTab(tabHost.newTabSpec("tab2")
        .setIndicator("分頁二")
        .setContent(R.id.view2));

tabHost.addTab(tabHost.newTabSpec("tab3")
        .setIndicator("分頁三")
        .setContent(R.id.view3));

四、實務提醒

TabActivity 屬於較早期的實作方式,在新版 Android 開發中,官方已建議改用 Fragment 搭配 TabLayout 或 ViewPager 來實作分頁,因為它具備更好的生命週期管理與版面適應能力。若只是維護既有專案,理解 TabHost 的運作方式仍有其價值。

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