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

Android UI 學習筆記:Tab 頁籤元件的完整用法

編輯:Android 開發實例

做 Android 介面時,「一個畫面切換多個子頁面」是很常見的需求。本文以官方 ApiDemos 中的 Views/Tabs 系列範例為藍本,把 TabActivity、TabHost、TabSpec 這條使用鏈條梳理清楚,並整理實作時容易踩到的細節。

TabActivity:最省力的起點

Android 提供 TabActivity 作為基底類別,讓我們不必自己組裝頁籤容器。幾個值得留意的成員函式:

public TabHost getTabHost():取得目前 TabActivity 的 TabHost。
public TabWidget getTabWidget():取得頁籤列(TabWidget)本身。
public void setDefaultTab(String tag) 與 public void setDefaultTab(int index):設定啟動時預設顯示的頁籤,可用 tag 名稱,也可用從 0 開始的索引。
protected void onSaveInstanceState(Bundle outState) 與 protected void onRestoreInstanceState(Bundle state):狀態的保存與還原,行為與 Activity 生命週期中的同名方法一致。

TabHost:頁籤真正的載體

TabHost 需透過 TabActivity.getTabHost() 取得。類別內部有三個要認識的成員:一個類別 TabHost.TabSpec,以及兩個介面 TabHost.TabContentFactory 與 TabHost.OnTabChangeListener。

常用函式:

public void addTab(TabHost.TabSpec tabSpec):新增一個頁籤。
public TabHost.TabSpec newTabSpec(String tag):建立 TabSpec 物件。
public void clearAllTabs():移除全部頁籤。
public int getCurrentTab() / getCurrentTabTag() / getCurrentTabView() / getCurrentView():查詢目前頁籤的索引、tag、內容 View 與實際顯示的 View。
public FrameLayout getTabContentView():取得承載頁籤內容的 FrameLayout。
public TabWidget getTabWidget():取得頁籤列。
public void setCurrentTab(int index) 與 setCurrentTabByTag(String tag):以索引或 tag 切換頁籤。
public void setOnTabChangedListener(TabHost.OnTabChangeListener l):註冊切換事件。
public void setup():初始化,使用時機見後文。

TabHost.TabSpec:tag、indicator、content 三件事

官方文件的一句話說明了 TabSpec 的職責:「A tab has a tab indicator, content, and a tag that is used to keep track of it.」也就是說,tag 只是內部識別用的標籤,並不是頁籤上顯示的文字,這點最容易搞混。

對應的三組方法:getTag()、setIndicator(...)、setContent(...)。

Indicator(頁籤外觀)有三種寫法:

setIndicator(CharSequence label):只設文字。
setIndicator(CharSequence label, Drawable icon):文字加圖示。
setIndicator(View view):直接指定自訂 View。

Content(頁籤內容)同樣有三種來源:

setContent(int viewId):指向版面檔中既有的 View。
setContent(TabHost.TabContentFactory contentFactory):由 Factory 動態產生。
setContent(Intent intent):直接把另一個 Activity 嵌進來。

寫法一:以 View ID 指定內容

官方 Views/Tabs/Content By Id 範例:

public class Tabs1 extends TabActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TabHost tabHost = getTabHost();

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

        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1")
                .setContent(R.id.view1));
        tabHost.addTab(tabHost.newTabSpec("tab2")
                .setIndicator("tab2")
                .setContent(R.id.view2));
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("tab3")
                .setContent(R.id.view3));
    }
}

取得 TabHost 之後,必須用 LayoutInflater 把版面塞進 tabHost.getTabContentView() 裡,這一步常被遺漏。R.layout.tabs1 的內容如下:

<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="tab1" />

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

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

所以頁籤內容的容器其實就是一個 FrameLayout,三個子 View 疊在同一層,切換頁籤時只切換可見性。搭配 setContent(R.id.view1),第一個頁籤便會顯示藍底、文字為 tab1 的 TextView。

寫法二:用 TabContentFactory 動態產生

Views/Tabs/Content By Factory 範例,讓 Activity 自己實作 Factory:

public class Tabs2 extends TabActivity implements TabHost.TabContentFactory {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final TabHost tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1", getResources().getDrawable(R.drawable.star_big_on))
                .setContent(this));
        tabHost.addTab(tabHost.newTabSpec("tab2")
                .setIndicator("tab2")
                .setContent(this));
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("tab3")
                .setContent(this));
    }

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

關鍵在於覆寫 View createTabContent(String tag),並把 setContent 的參數設為這個 Factory。

實作上很重要的一點:createTabContent 只會在該頁籤「第一次」顯示時被呼叫,之後再切回來不會重新觸發。由於此時頁籤尚未完全建立完成,在 createTabContent 裡呼叫 getCurrentTabView() 這類方法會出錯,務必避免。

寫法三:用 Intent 嵌入其他 Activity

Views/Tabs/Content By Intent 範例:

public class Tabs3 extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final TabHost tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("list")
                .setContent(new Intent(this, List1.class)));

        tabHost.addTab(tabHost.newTabSpec("tab2")
                .setIndicator("photo list")
                .setContent(new Intent(this, List8.class)));

        // 這個頁籤加上 flag,每次點擊都會重建
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("destroy")
                .setContent(new Intent(this, Controls2.class)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
    }
}

效果是:tab1 顯示 List1、tab2 顯示 List8、tab3 顯示 Controls2。第三個刻意加上 FLAG_ACTIVITY_CLEAR_TOP,示範如何讓內容在每次點擊時重新建立。

TabHost.OnTabChangeListener

這個介面只有一個方法 onTabChanged(String tagString)。實作時用 switch…case 判斷 tagString 分頭處理即可。

setup() 到底何時要呼叫

官方文件的說法很明確:自 API Level 1 起,若你是用 findViewById() 取得 TabHost,就必須在 addTab 之前先呼叫 setup();但如果是透過 TabActivity 的 getTabHost() 取得,則不需要再呼叫。

mTabHost = (TabHost)findViewById(R.id.tabhost);
mTabHost.setup();
mTabHost.addTab(...);

另一個多參數版本 setup(LocalActivityManager activityGroup):只要你使用 setContent(android.content.Intent),就必須提供 activityGroup 才能啟動頁籤內的本地 Activity。這一步在繼承 TabActivity 時已由系統代為完成。

小結

Tab 的實作骨架其實很固定:取得 TabHost →(必要時)inflate 版面 → 逐一 newTabSpec 並設定 indicator 與 content → 需要時掛上 OnTabChangeListener。真正需要多花心思的是 content 的選擇:靜態版面用 View ID,需要延遲建立或客製化時用 Factory,要複用既有 Activity 時用 Intent。另外提醒,TabActivity 屬於較早期的寫法,新專案通常會改用 ViewPager 搭配 Fragment 來達成相同效果,但理解 TabHost 的思維仍有助於看懂舊程式碼。

本文整理自「學習Android」部落格:https://android.blog.51cto.com/268543/315208

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