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

TabWidget 實作教學:TabHost 版面結構與 Java 端標籤動態掛載

編輯:關於 Android 開發

TabWidget 的作用

TabWidget 提供一排可切換的標籤,每個標籤對應一段內容,運作起來像是一組「互斥的按鈕」——選中哪一個,就顯示哪一個對應的畫面。在 TabLayout 與 ViewPager 普及之前,這是 Android 做分頁切換的標準做法。

版面結構怎麼湊出來

TabHost 的 XML 結構有點繁瑣,用 GUI 拉出來的骨架又常自帶多餘的巢狀 LinearLayout。整理後的目標結構是這樣:

TabHost(ID 必須是 @android:id/tabhost)→ LinearLayout(直向)→ 裡面依序放 TabWidget(ID 為 @android:id/tabs)與 FrameLayout(ID 為 @android:id/tabcontent)。

這三個 ID 是 TabHost 內部查找子 View 的固定依據,寫錯就會在 getTabHost() 時出問題。

實作上的小技巧:先在 Layouts 拉一個直向 LinearLayout,再從 Composite 拖入 TabHost(它會自動帶三層 LinearLayout),把多餘的巢狀層刪掉,最後把 xmlns 命名空間宣告搬到 TabHost 上即可。

完成後 FrameLayout 就是內容容器,把各頁的 View 直接放進去當作標籤內容使用。

activity_main.xml

<TabHost xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

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

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

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="414dp">

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#00FF00"
                android:text="TextView" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#FF0000"
                android:text="TextView" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#0099CC"
                android:text="TextView" />
        </FrameLayout>
    </LinearLayout>
</TabHost>

MainActivity

注意這裡必須繼承 TabActivity(而非一般的 Activity),才能用 getTabHost() 取得 TabHost 實例。

package com.example.tabwidgetdemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;

public class MainActivity extends TabActivity {

    private TabHost tabHost;

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

        tabHost = getTabHost();

        // 掛上各個標籤
        addTab();

        // 設定背景顏色與背景圖
        tabHost.setBackgroundColor(Color.argb(150, 20, 50, 150));
        tabHost.setBackgroundResource(R.drawable.a);

        // 預設停在第一頁
        tabHost.setCurrentTab(0);

        tabHost.setOnTabChangedListener(new OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabID) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("當前選中了" + tabID + "標簽");
                builder.setPositiveButton("確定", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                Dialog dialog = builder.create();
                dialog.show();
            }
        });
    }

    /** 逐一掛上標籤:tag 名稱、指示器(文字+圖示)、對應的內容 View */
    private void addTab() {
        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("TAB1", getResources().getDrawable(R.drawable.a))
                .setContent(R.id.textView1));

        tabHost.addTab(tabHost.newTabSpec("tab2")
                .setIndicator("TAB2", getResources().getDrawable(R.drawable.a))
                .setContent(R.id.textView2));

        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("TAB3", getResources().getDrawable(R.drawable.a))
                .setContent(R.id.textView3));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

執行效果:

addTab 的三個環節

每一次 addTab() 呼叫由三段串接構成,各自負責不同的事:

  • newTabSpec("標籤識別碼"):這個字串就是 onTabChanged() 收到的 tabID。
  • setIndicator(文字, 圖示):決定標籤上顯示什麼。也有單參數版本,可傳入自訂 View 做完全客製的樣式。
  • setContent(...):決定這一頁顯示什麼。可以傳 view ID(如上例),也可以傳 Intent 或 TabContentFactory。

為什麼不建議在新專案使用 TabActivity

TabActivity 與 TabHost 都已被標記為已棄用(deprecated)。原因在于這種設計把分頁邏輯寫死在 Activity 裡,難以 reuse,也無法與 Fragment 生命週期整合。

現代做法有兩種選擇:TabLayout + ViewPager2(可滑動切頁,最常用),或 TabLayout + FragmentContainerView(頁籤切換 Fragment)。兩者都能搭配 TabLayoutMediator 把頁籤與分頁器綁在一起,程式碼量比 TabHost 少,行為也更符合 Material Design 規範。

若你只是維護一個舊專案、暫時不想大改,理解 TabHost 的運作方式仍然有價值;但如果是新專案,直接上 TabLayout 會省下不少力氣。

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