Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 頂部導航欄實作:類網易新聞的版面與記憶體考量

為什麼需要頂部導航

行動裝置螢幕有限,內容卻越來越多。底部選單欄解決了主要功能入口,但當頻道數量多、又希望在主頁直接呈現時,就得再加上一層頂部導航。問題是 Android 裝置的記憶體受限,若把大量界面與圖片都快取在記憶體中,很容易觸發 OutOfMemoryError,這是足以讓應用當掉的致命錯誤,必須提前規劃。

先前曾用 ViewPager 實作類似效果,但每頁都是複雜版面、圖片佔用又多,記憶體吃緊。這次改用「 RadioGroup 切換 + 單一容器動態填充」的作法,同一時間只存在一個頁面的视图,壓力小得多,值得兩者對照比較。

版面:head.xml 與主檔

頂部標題列獨立成 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 仍是最省事的選擇;一旦頁面較重,就該回到動態填充的路線。選型的依據不是流行與否,而是每頁的記憶體成本。

Copyright © Linux教程網 All Rights Reserved