Tab 標籤頁控制項在許多程式技術中都見得到,它能讓視窗顯示區被重複利用。在 Android 中,標籤頁會牽涉到 TabActivity、TabHost、TabWidget 等概念。善用 Tab 標籤頁控制項,就能在同一個空間裡塞進更多內容。舉例來說,Android 自帶的撥號程式與通訊錄,就運用了 Tab 標籤功能,如下圖所示:

下面我們用實作的方式,來學習如何做出類似的效果,其實還蠻簡單的。我同樣把說明寫進範例的註解裡,註解是我的理解,未必百分百精準,只是方便你記憶。
1、新建一個專案 Lesson44_Tab,Activity 取名為 MainActivity。
2、編寫 main.xml,內容如下。這次的寫法與一般版面配置檔略有不同,請注意:
- <?xml version="1.0" encoding="utf-8"?>
- <!-- 根元素是 TabHost,這個檔要與 TabActivity 搭配使用,在 TabActivity 的源碼裡寫死了要找的 Id 是 android.R.id.tabhost,
- 因此這裡的 ID 也要定死成 TabHost 的 ID "@android:id/tabhost",下面的類似,不再解釋。 -->
- <TabHost xmlns:android="https://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent">
- <!-- TabWidget 就是標籤選項卡的頭部部分,注意 ID 的寫法 -->
- <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content">
- </TabWidget>
- <!-- FrameLayout 就是標籤的內容顯示部分,注意 ID 的寫法,還要注意我們做了個上部空白設定 android:paddingTop="65dp",是為了不讓內容和標籤重疊 -->
- <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingTop="65dp">
- <!-- LinearLayout 是一個標籤裡的內容,程式根據你定義的 ID 來把他們放在不同的標籤下面 -->
- <LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content">
- <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="標籤1中的內容">
- </TextView>
- </LinearLayout>
- <!-- LinearLayout 是另一個標籤裡的內容 -->
- <LinearLayout android:id="@+id/linearLayout2" android:layout_width="wrap_content" android:layout_height="wrap_content">
- <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="標籤2中的內容">
- </TextView>
- </LinearLayout>
- </FrameLayout>
- </TabHost>
3、編寫 MainActivity,請注意它繼承的是 TabActivity 類,說明都寫在程式碼裡:
- package basic.android.lesson44;
- import android.app.TabActivity;
- import android.os.Bundle;
- import android.widget.TabHost;
- public class MainActivity extends TabActivity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // tabHost 是一個標籤容器
- TabHost tabHost = this.getTabHost();
- // 每一個 TabSpec 物件就是個標籤
- // TabSpec.setIndicator() 方法是設定標籤顯示樣式
- // TabSpec.setContent() 方法是設定標籤下方的內容顯示
- // 定義第一個標籤
- tabHost.addTab(tabHost.newTabSpec("OneTab")
- .setIndicator("OneTab", getResources().getDrawable(android.R.drawable.star_on))
- .setContent(R.id.linearLayout1));
- // 定義第二個標籤
- tabHost.addTab(tabHost.newTabSpec("TwoTab")
- .setIndicator("TwoTab", getResources().getDrawable(android.R.drawable.star_off))
- .setContent(R.id.linearLayout2));
- }
- }
4、編譯程式、運行程式碼,查看結果:

點擊 TwoTab,標籤切換:

建議大家先讀一遍註解,等程式跑起來後再對照理解,印象會更深刻。本節就講到這裡。