編輯:開發入門
智慧型手機的螢幕尺寸先天受限,所以在做 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 直接掛成一個分頁時用方式二。依照你的實際架構挑一個合適的即可。
Android 2.2 開發環境建置全攻略(Windows 篇)
本文以 Windows 7 為示範平台,記錄從 JDK 安裝一路到建立並啟動 AVD 的完整流程。 環境概要 作業系統:Windows 7 JDK:java ver
Android 上的 XML 與 JSON 實戰(上):從格式基礎到 Twitter feed 解析
簡介:這個兩 Part 的系列要談的是行動平台上處理資料交換格式的實務——XML 與 JavaScript Object Notation(JSON)。第一篇先把兩種格式
用 Eclipse 與 Android 元件做開發(一):觀念、環境與 AVD 建置
先搞懂 Android 的幾個關鍵術語 一個典型的 Android 應用由幾類元件組成。以下先列出主要四種,並附上 Android 開發者網站的定義: 活動(Activ
Android XML 菜單:menu、group 與 item 的配置方式
在 XML 中定義菜單 Android 的菜單可以透過程式建立,也可以放在 XML 資源中。使用 XML 的好處是結構清楚、易於維護,也能把界面設計與程式邏輯分離。 me