底部選單欄幾乎是行動應用的標準配備。本文用 TabHost 搭一個可重複使用的骨架,並示範如何在圖示上方顯示未讀訊息數量——像微信那樣的小紅點。
先前的版本在 layout 裡堆了太多不必要的嵌套層,效能與可讀性都不理想。這次把多餘的層拿掉,只保留必要結構,後續只要替換圖片與文字樣式,主框架完全不用動。
整體是 TabHost 包一個 LinearLayout,內部由上而下分三塊:FrameLayout(id 為 @android:id/tabcontent)放內容、TabWidget(@android:id/tabs)保留但隱藏、最下方自繪的 RadioGroup 作為真正的選單列。未讀紅點則是疊在 RadioGroup 之上的 TextView。
<?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bg_gray"
android:orientation="vertical" >
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0.0dip"
android:layout_weight="1.0" />
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.0"
android:visibility="gone" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RadioGroup
android:id="@+id/main_tab_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="@drawable/bottom1"
android:gravity="bottom"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/main_tab_addExam"
style="@style/MMTabButton"
android:layout_weight="1.0"
android:drawableTop="@drawable/bg_checkbox_icon_menu_0"
android:text="添加考試" />
<RadioButton
android:id="@+id/main_tab_myExam"
style="@style/MMTabButton"
android:layout_weight="1.0"
android:checked="true"
android:drawableTop="@drawable/bg_checkbox_icon_menu_1"
android:text="我的考試" />
<RadioButton
android:id="@+id/main_tab_message"
style="@style/MMTabButton"
android:layout_weight="1.0"
android:drawableTop="@drawable/bg_checkbox_icon_menu_2"
android:text="我的通知" />
<RadioButton
android:id="@+id/main_tab_settings"
style="@style/MMTabButton"
android:layout_weight="1.0"
android:drawableTop="@drawable/bg_checkbox_icon_menu_3"
android:text="設置" />
</RadioGroup>
<TextView
android:id="@+id/main_tab_new_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:layout_marginLeft="60dip"
android:layout_marginTop="1dip"
android:background="@drawable/tips"
android:gravity="center"
android:text="1"
android:textColor="#ffffff"
android:textSize="10sp"
android:visibility="gone" />
</FrameLayout>
</LinearLayout>
</TabHost>
隱藏 TabWidget 是因為要完全自繪樣式,但保留 TabHost 的內容切換能力,兩者各取所長。
RadioGroup 天然具備單選互斥特性,四個 RadioButton 各配 layout_weight="1.0" 就能等寬平分,不必自己算像素;切換狀態則靠 drawableTop 搭配 selector 圖示自動切換。
未讀紅點用 layout_marginLeft="60dip" 做粗略定位,這是這類寫法最脆弱的一環——換圖示尺寸就得重調。若要更穩健,可把紅點放進每個 tab 的獨立容器版面,用 RelativeLayout 對齊右上角。
Java 端只需在 RadioGroup 上掛 OnCheckedChangeListener,依被選中的 id 呼叫 setCurrentTab 切換內容,並在需要時把紅點的 visibility 設為 GONE。