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

Android 面板控件 TabHost 的兩種內容綁定方式

編輯:關於 Android 開發

手機螢幕就那麼大,當要在一個畫面裡塞進大量內容時,最直接的反應是讓版面可以捲動。但捲動看起來終究不夠俐落,而且當不同功能的控制項本就該分組呈現時,把它們各自收進一個面板、用標籤切換,才是更合適的選擇。這正是 Tab 控件的用武之地。

面板控件的好處很明確:同一個畫面上容納多組內容,使用者透過標籤就能在面板之間快速切換,而不必在長長的捲動列表中尋找。以下直接從範例出發,介紹 Tab 的兩種內容設置方式。

先在版面中定義各面板內容

最直白的做法,是在 XML 裡把每個 Tab 要顯示的內容都準備好。這裡以兩個 TextView 為例:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- Tab 1 中顯示的內容 -->
    <TextView
        android:id="@+id/content1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="tab1 content" />

    <!-- Tab 2 中顯示的內容 -->
    <TextView
        android:id="@+id/content2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="tab2 content" />
</FrameLayout>

這裡之所以用 FrameLayout 當外層容器,是因為它的子元素預設互相重疊,而 TabHost 在切換時會控制各面板的可見性——同一時間只有一個內容顯示。

在程式碼中掛上 Tab

接著在 Activity 中取得 TabHost,把版面 inflate 進去,再逐一加入各個 Tab:

public class _Tab extends TabActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TabHost tabHost = getTabHost();
        LayoutInflater.from(this).inflate(R.layout.tab, tabHost.getTabContentView(), true);

        // Tab 1 的內容
        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1", getResources().getDrawable(R.drawable.p1))
                .setContent(R.id.view1));

        // Tab 2 的內容
        tabHost.addTab(tabHost.newTabSpec("tab2")
                .setIndicator("tab2", getResources().getDrawable(R.drawable.p1))
                .setContent(R.id.view2));

        // Tab 3 的內容:直接指定一個 Activity 作為面板內容
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("tab3", getResources().getDrawable(R.drawable.p1))
                .setContent(new Intent(this, _TextView.class)));
    }
}

三個關鍵方法

從範例可以看出,Tab 的使用主要繞著三個方法打轉:

  • addTab():把一個 TabSpec 加入 TabHost。
  • setIndicator():設定標籤的文字與圖示。
  • setContent():綁定這個面板要顯示的內容。

而 setContent 正是兩種做法的分水嶺。傳入一個 view id(如 R.id.view1)時,面板內容來自版面檔中已定義好的控制項;傳入一個 Intent 時,則是把另一個 Activity 直接作為面板內容顯示。

第二種方式在實務上特別有用:它讓每個 Tab 的內容在邏輯上完全獨立開來,各自擁有完整的生命週期,不必擠在同一個 Activity 裡互相牽扯。當你的面板內容各自由不同功能組成、狀態管理也互不相干時,用 Activity 當內容會讓整體結構清爽許多。

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