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

Android TabHost 標籤頁的四種實作方式

編輯:關於 Android 程式設計

Tab 標籤是 Android 早期常見的 UI 元件,核心類別是 TabHost。本文用四個由淺入深的例子把它的用法完整走一遍,最後再談談為什麼現在已經不建議使用它。

TabHost 的結構

TabHost 是一個標籤頁的容器,內部包含兩個必要子元素:

  • TabWidget:橫向排列的標籤集合,使用者點擊其中之一來切換頁面。
  • FrameLayout:承載目前所選頁面的內容。

這兩個子元素通常由 TabHost 本身管理,而不是直接操作。

第一種:繼承 TabActivity

最直白的做法,TabActivity 已經幫你把 TabHost 準備好:

public class HelloTabActivity extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TabHost tabHost = getTabHost();

        // 把布局載入到 TabHost 的內容區
        LayoutInflater.from(this).inflate(
                R.layout.activity_hello_tab, tabHost.getTabContentView(), true);

        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1 indicator")
                .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));
    }
}

內容布局是一個 FrameLayout,裡面放三個 TextView,各自對應一個頁籤:

<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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/blue"
        android:text="@string/tab1" />

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

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

用到的顏色資源定義在 colors.xml:

<resources>
    <drawable name="red">#7f00</drawable>
    <drawable name="blue">#770000ff</drawable>
    <drawable name="green">#7700ff00</drawable>
    <drawable name="yellow">#77ffff00</drawable>
    <color name="solid_red">#f00</color>
    <color name="solid_blue">#0000ff</color>
    <color name="solid_green">#f0f0</color>
    <color name="solid_yellow">#ffffff00</color>
</resources>

要注意 TabActivity 這個類別在 API level 13 就已被標記為 deprecated。

第二種:用 TabContentFactory 動態產生內容

TabHost.TabContentFactory 這個介面的用途是「在頁籤被選中時即時產生內容」,而不是事先放一個 View 進去或啟動另一個 Activity。實作這個介面後,把 setContent(this) 傳進去即可:

public class HelloTabActivity extends TabActivity implements TabHost.TabContentFactory {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TabHost tabHost = getTabHost();

        // 注意:這次不需要載入內容布局,若保留會導致內容重疊
        // LayoutInflater.from(this).inflate(R.layout.activity_hello_tab,
        //         tabHost.getTabContentView(), true);

        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1 indicator").setContent(this));
        tabHost.addTab(tabHost.newTabSpec("tab2")
                .setIndicator("tab2").setContent(this));
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("tab3").setContent(this));
    }

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

補充一點:頁籤的內容也可以用 Intent 指定,也就是點下去啟動另一個 Activity。做法是 setContent(Intent) 而非 setContent(int),細節可參考 ApiDemos 的 Tabs3.java。

第三種:不繼承 TabActivity

如果不想被 TabActivity 綁住(畢竟它已 deprecated),就得自己寫 TabHost 的布局。關鍵是兩個子元素的 id 必須使用系統預defined值:

<TabHost android:id="@+id/myTabHost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- id 必須是 @android:id/tabs -->
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- id 必須是 @android:id/tabcontent -->
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/view1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Tab1 Content" />

            <TextView
                android:id="@+id/view2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Tab2 Content" />
        </FrameLayout>
    </LinearLayout>
</TabHost>

Activity 端則必須自行呼叫 setup():

public class HelloTabHostActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_tab_host);

        TabHost tabHost = (TabHost) findViewById(R.id.myTabHost);

        // 不繼承 TabActivity 時,務必在 addTab 之前呼叫 setup()
        tabHost.setup();

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

這種做法的靈活度最高:你可以在 TabHost 之外自由加入其他元件,也能任意調整標籤欄與內容區的相對位置。

第四種:可捲動的標籤列

當頁籤數量多到一排放不下時,把 TabWidget 包進 HorizontalScrollView 就能橫向捲動:

<TabHost android:id="@+id/myTabHost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="5dp">

        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="none">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </HorizontalScrollView>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="5dp" />
    </LinearLayout>
</TabHost>
public class HelloTabScrollActivity extends Activity implements TabHost.TabContentFactory {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_tab_scroll);

        TabHost tabHost = (TabHost) findViewById(R.id.myTabHost);
        tabHost.setup();

        // 一次加上 30 個標籤
        for (int i = 1; i <= 30; i++) {
            String name = "Tab " + i;
            tabHost.addTab(tabHost.newTabSpec(name)
                    .setIndicator(name).setContent(this));
        }
    }

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

現在該用什麼

把四種寫法看完,你大概也能感覺到 TabHost 的彆扭之處:TabActivity 已废弃、id 必須寫死成系統值、setup() 的呼叫時機容易出錯、標籤外觀幾乎無法客製、也沒有 Fragment 生命週期管理與 ViewPager 的滑動切換。

現代 Android 的標準答案是 TabLayout 搭配 ViewPager(或 ViewPager2):標籤樣式、指示器、選中顏色都能直接透過 XML 設定,切換時還能與 Fragment 生命週期正確整合。若你只是維護一個老專案,理解 TabHost 的運作方式仍有價值;但若是新專案,請直接從 TabLayout 開始。

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