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

用 TabHost 整合多個 Activity,讓手機 GUI 不再臃腫

編輯:開發入門

智慧型手機的螢幕尺寸先天受限,所以在做 GUI 優化時,一般不太建議把過多元素塞進同一個 Activity。最直接的解法是把介面拆成好幾個 Activity,各自獨立呼叫。

這樣做表面問題是解決了,卻衍生出新的麻煩:有些操作本身內聚性很強,硬拆開之後使用起來反而變得斷斷續續,操作體驗的流暢度下降,整體性也被破壞。

這裡介紹一個比較「溫馨」的折衷方案:用 Widget.TabHost 把多個 Activity 合併回同一個 Activity 裡。這樣同時解決了兩件事——一來避免單一 Activity 元素過多而顯得笨重,二來不必把高內聚的複雜操作拆散,系統整體性得以保留。

有經驗的人看下面的範例大概就能猜到每段方法在做什麼;如果你剛入門,可以先這樣理解 TabHost:它就像瀏覽器上用來切換不同頁面的那排分頁標籤。

先定義版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TabHost
        android:id="@+id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="105px" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:paddingTop="65px">

            <LinearLayout
                android:id="@+id/tab1content"
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#00008B">
                <!-- 第一個分頁的內容放這裡 -->
            </LinearLayout>

            <LinearLayout
                android:id="@+id/tab2content"
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#FFFF00">
                <!-- 第二個分頁的內容放這裡 -->
            </LinearLayout>

        </FrameLayout>
    </TabHost>
</LinearLayout>

這裡每個 LinearLayout 就是各自獨立分頁(TabHost.TabSpec)所對應的內容容器。

兩種填充分頁的方式

方式一:直接指向版面中的某個容器。適合在同一個 Activity 內部切分不同區塊:

TabHost tabs = (TabHost) this.findViewById(R.id.tabhost);
tabs.setup();

TabHost.TabSpec one = tabs.newTabSpec("one");
one.setContent(R.id.tab1content);
one.setIndicator("TAB 1");
tabs.addTab(one);

方式二:把外部 Activity 當成分頁內容。此時傳入的是 Intent 物件,等於把另一個 Activity 類別嵌進目前的實體中:

TabHost host = getTabHost();
host.addTab(host.newTabSpec("one").setIndicator("TAB1")
        .setContent(new Intent(this, Tab1Activity.class)));
host.addTab(host.newTabSpec("two").setIndicator("TAB2")
        .setContent(new Intent(this, Tab2Activity.class)));

其中 Tab1Activity 與 Tab2Activity 是兩個獨立的 Activity 類別,宣告好的實體會被植入 TabSpec 裡頭。

兩種寫法各有適用場景:需要快速切換畫面區塊時用方式一,想把既有的完整 Activity 直接掛成一個分頁時用方式二。依照你的實際架構挑一個合適的即可。

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