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

Android TabActivity 用法整理:TabHost 與 TabSpec 完整解析

編輯:關於 Android 程式設計

Android 早期提供了 TabActivity 這個方便的類別,讓我們能快速做出分頁切換的效果。要理解它,先從相關的幾個核心類別與方法開始。

TabActivity 的關鍵方法

public TabHost getTabHost()
取得當前 TabActivity 的 TabHost 容器。

public TabWidget getTabWidget()
取得當前 TabActivity 的 TabWidget,也就是畫面上那一排分頁標籤的元件。

public void setDefaultTab(String tag) 與 public void setDefaultTab(int index)
設定預設顯示的分頁,可以用分頁的 tag 名稱,也可以用 index(從 0 開始)。

protected void onSaveInstanceState(Bundle outState) 與 protected void onRestoreInstanceState(Bundle state)
狀態的保存與還原,行為與 Activity 生命週期一致。

TabHost:分頁的載體

TabHost 是真正承載分頁的容器,需透過 TabActivity.getTabHost() 取得。TabHost 類別包含三個內嵌型別:類別 TabHost.TabSpec,以及介面 TabHost.TabContentFactory 與 TabHost.OnTabChangeListener。

TabHost 的常用方法:

・public void addTab(TabHost.TabSpec tabSpec):新增一個分頁,參數由下面的 newTabSpec() 取得
・public TabHost.TabSpec newTabSpec(String tag):建立 TabSpec 物件
・public void clearAllTabs():移除全部分頁
・public int getCurrentTab()/getCurrentTabTag()/getCurrentTabView()/getCurrentView():取得當前分頁的相關資訊
・public FrameLayout getTabContentView():回傳承載分頁內容的 FrameLayout
・public TabWidget getTabWidget():取得分頁標籤元件
・public void setCurrentTab(int index)/setCurrentTabByTag(String tag):依 index 或 tag 切換分頁
・public void setOnTabChangedListener(TabHost.OnTabChangeListener l):設定分頁切換事件的回呼
・public void setup():初始化 TabHost 的必要呼叫

TabHost.TabSpec:管理三件事

從上面的方法可以看出新增分頁的流程。這裡要特別提醒:newTabSpec() 傳入的 tag 並不是分頁按鈕上顯示的文字,它只是一個用來追蹤該分頁的標識符。

真正要設定分頁的 label 與內容,必須透過 TabSpec。官方文件的說法是:「A tab has a tab indicator, content, and a tag that is used to keep track of it.」TabSpec 就是管理這三樣東西:

public String getTag()
取得該分頁的 tag。

public TabHost.TabSpec setIndicator(...)
設定 indicator,也就是分頁上的標示,有三種寫法:

・setIndicator(CharSequence label):只設定文字
・setIndicator(CharSequence label, Drawable icon):同時設定文字與圖示
・setIndicator(View view):直接指定一個自訂 View 當作標示

public TabHost.TabSpec setContent(...)
設定分頁裡的內容,同樣有三種方式:

・setContent(int viewId):指定版面配置中某個 View 的 id
・setContent(TabHost.TabContentFactory contentFactory):由 Activity 實作工廠介面,在 createTabContent(String tag) 中動態產生內容 View
・setContent(Intent intent):用 Intent 引入其他 Activity 的內容

實作一:直接指定 View id

Activity 程式碼:

package com.yang.tabletest;

import android.app.TabActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TabHost;

public class TableTestAcitivity extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);

        // 獲得當前 TabActivity 的 TabHost
        TabHost tabHost = getTabHost();

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

        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));
        tabHost.addTab(tabHost.newTabSpec("tab4")
                .setIndicator("關於")
                .setContent(R.id.view4));
    }
}

tabs1.xml(版面內容):

<frameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:id="@+id/view1"
        android:background="@drawable/blue"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="@string/tabs_1_tab_1"/>

    <TextView android:id="@+id/view2"
        android:background="@drawable/red"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="@string/tabs_1_tab_2"/>

    <TextView android:id="@+id/view3"
        android:background="@drawable/green"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="@string/tabs_1_tab_3"/>

    <TextView android:id="@+id/view4"
        android:background="@drawable/green"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="@string/tabs_1_tab_4"/>
</frameLayout>

string.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, TableTestAcitivity!</string>
    <string name="app_name">阿福學習</string>
    <string name="tabs_1_tab_1">主頁</string>
    <string name="tabs_1_tab_2">標題</string>
    <string name="tabs_1_tab_3">關於</string>
    <string name="tabs_1_tab_4">返回</string>
</resources>

color.xml(以 drawable 形式定義顏色):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <drawable name="darkgray">#404040ff</drawable>
    <drawable name="red">#ff00ff</drawable>
    <drawable name="green">#0ff0ff</drawable>
    <drawable name="lightgray">#c0c0c0ff</drawable>
    <drawable name="yellow">#ffFF33ff</drawable>
    <drawable name="blue">#00ffff</drawable>
    <drawable name="gray">#808080ff</drawable>
    <drawable name="magenta">#ff6699ff</drawable>
    <drawable name="cyan">#66ffffff</drawable>
    <drawable name="black">#000000</drawable>
    <drawable name="white">#FFFFFF</drawable>
</resources>

實作二:用 TabContentFactory 動態產生內容

如果每個分頁的內容需要在執行期動態產生,可以讓 Activity 實作 TabHost.TabContentFactory,並搭配 setIndicator(label, icon) 加上圖示:

package com.yang.tabletest;

import android.app.TabActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;

public class TableTestAcitivity extends TabActivity implements TabHost.TabContentFactory {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final TabHost tabHost = getTabHost();
        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("主頁", getResources().getDrawable(R.drawable.test))
                .setContent(this));
        tabHost.addTab(tabHost.newTabSpec("tab2")
                .setIndicator("標題", getResources().getDrawable(R.drawable.test))
                .setContent(this));
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("關於", getResources().getDrawable(R.drawable.test))
                .setContent(this));
    }

    @Override
    public View createTabContent(String arg0) {
        final TextView tv = new TextView(this);
        tv.setText("Content for tab with tag " + arg0);
        return tv;
    }
}

範例執行結果與專案下載:

・TableTest.zip(25.4 KB,下載次數 563)

・TableTest2.zip(29.8 KB,下載次數 487)

補充說明

值得留意的是,TabActivity 在 Android 3.0 之後已被標記為 deprecated。官方建議改用 Fragment 搭配 TabLayout(來自 Android Design Support Library)或 ViewPager 來實作分頁,因為 Fragment 方案在生命週期管理、記憶體效率與樣式自訂上都更成熟。若是維護舊專案,理解 TabHost 的運作方式仍然有幫助;若是新專案,直接採用 TabLayout + ViewPager 會省事得多。

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