行動裝置螢幕有限,內容卻越來越多。底部選單欄解決了主要功能入口,但當頻道數量多、又希望在主頁直接呈現時,就得再加上一層頂部導航。問題是 Android 裝置的記憶體受限,若把大量界面與圖片都快取在記憶體中,很容易觸發 OutOfMemoryError,這是足以讓應用當掉的致命錯誤,必須提前規劃。
先前曾用 ViewPager 實作類似效果,但每頁都是複雜版面、圖片佔用又多,記憶體吃緊。這次改用「 RadioGroup 切換 + 單一容器動態填充」的作法,同一時間只存在一個頁面的视图,壓力小得多,值得兩者對照比較。
頂部標題列獨立成 head.xml,主版面用 <include> 引入,日後改動不影響主結構。導航列同樣用 RadioGroup 承載,下方預留一個 id 為 container 的 LinearLayout 作為內容容器。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<include layout="@layout/head" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioGroup
android:id="@+id/add_tab_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="6dp"
android:paddingBottom="6dp"
android:background="@drawable/big_button_up"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/main_tab_addExam"
style="@style/MMTabButton1"
android:layout_weight="1.0"
android:checked="true"
android:text="添加考試" />
<RadioButton
android:id="@+id/main_tab_myExam"
style="@style/MMTabButton1"
android:layout_weight="1.0"
android:text="我的考試" />
<RadioButton
android:id="@+id/main_tab_testing"
style="@style/MMTabButton1"
android:layout_weight="1.0"
android:text="測試" />
<RadioButton
android:id="@+id/main_tab_settings"
style="@style/MMTabButton1"
android:layout_weight="1.0"
android:text="設置" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
</LinearLayout>
</LinearLayout>
頂部導航的項目通常只放文字,靠 drawableTop 的圖示辨識度低,因此樣式改用 MMTabButton1,並以 layout_weight 等寬分配。选中態的視覺回饋一般由 style 內的 text color selector 負責,這也是把樣式抽到 style 的好處:版面檔乾淨,換風格只改一處。
第一,同一時間只載入一個頁面,切換時移除舊视图,別讓它們並存。
第二,圖片依顯示尺寸做 downsample 後再載入,不要直接 decode 原始檔。
第三,在 onTrimMemory 或 onLowMemory 中主動釋放非必要的快取。
若頁面數量固定且都很輕量,ViewPager 加上合適的 setOffscreenPageLimit 仍是最省事的選擇;一旦頁面較重,就該回到動態填充的路線。選型的依據不是流行與否,而是每頁的記憶體成本。