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

Android 介面開發入門:TabHost 分頁控件的兩種實作方式

編輯:中階開發

手機螢幕就那么幾吋,想把大量資訊一次塞進去,往往逼得我們只能做上下捲動。捲動當然可行,但視覺上零碎又凌亂;更麻煩的是,當畫面上同時存在好幾組功能彼此獨立的控制項時,硬擠在一頁裡只會讓使用者迷失。這正是分頁式面板(TabHost)存在的理由。

為什麼要用 Tab 面板

Tab 控件最大的價值,在於同一個畫面容器裡可以承載多份內容,並透過頂端或側邊的標籤讓使用者一鍵切換。每一頁各自負責一類資訊,切換成本極低,畫面也保持乾淨。

第一步:在版面檔裡準備各頁的內容

最直觀的做法,是先把每個分頁要顯示的 View 全部放進同一個 FrameLayout,讓它們重疊佔位,再由 TabHost 決定誰該露出來。以下用兩個 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>

第二步:在程式裡掛上 Tab

Activity 必須繼承 TabActivity,透過 getTabHost() 取得容器,再用 addTab() 一頁一頁加進去:

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:直接指向版面中的 View
        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1", getResources().getDrawable(R.drawable.p1))
                .setContent(R.id.vIEw1));

        // Tab 2:同樣用版面中的 View
        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)));
    }
}

三個關鍵方法

整套 API 其實只繞著三個方法打轉:
addTab() 負責把一個 TabSpec 註冊進 TabHost;
setIndicator() 決定標籤上顯示的文字與圖示;
setContent() 決定這一頁背後真正的內容是什麼。

其中 setContent() 有兩種截然不同的玩法:一種是傳入 view 的 id,讓內容沿用同一個 Activity 的版面;另一種是傳入 Intent,把另一個 Activity 整個塞進來當內容。後者最大的好處是職責分離——每個分頁各自擁有自己的生命週期與邏輯,不必把全部程式碼硬塞進同一支 Activity,維護起來清爽許多。

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