底部導航欄是 Android 應用中極為常見的 UI 模式,方便用戶在主要功能模組間快速切換。傳統實現方式包括自定義 TabHost、ActivityGroup 或結合 FrameLayout,但這些方案往往代碼冗餘、維護困難。本文介紹一種封裝抽象類的方案,僅需三步即可完成底部導航欄的構建與頁面切換邏輯。
將底部導航欄的通用邏輯(佈局初始化、Tab 項管理、Fragment/Activity 切換)封裝至 ActivityCollection 基類,子類僅需專注於業務配置。
將封裝好的庫項目(或 AAR/JAR)添加至項目依賴中,確保 ActivityCollection、IndicatorInfo 等核心類可用。
public class MainActivity extends ActivityCollection {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 可選:setBottomTabBackground(R.drawable.tab_bg); // 設置底部欄背景
}
@Override
protected boolean isShowWindowFeature() {
return true; // 是否顯示標題欄
}
@Override
protected List setDrawableCollections() {
List indicators = new ArrayList<>();
// 參數:默認圖標、選中圖標、標題文字資源、文字大小、文字顏色、目標 Activity Intent
indicators.add(new IndicatorInfo(
R.drawable.tab_home_normal, R.drawable.tab_home_selected,
R.string.tab_home, 12, Color.WHITE,
new Intent(this, HomeActivity.class)
));
indicators.add(new IndicatorInfo(
R.drawable.tab_discover_normal, R.drawable.tab_discover_selected,
R.string.tab_discover, 12, Color.WHITE,
new Intent(this, DiscoverActivity.class)
));
indicators.add(new IndicatorInfo(
R.drawable.tab_message_normal, R.drawable.tab_message_selected,
R.string.tab_message, 12, Color.WHITE,
new Intent(this, MessageActivity.class)
));
indicators.add(new IndicatorInfo(
R.drawable.tab_profile_normal, R.drawable.tab_profile_selected,
R.string.tab_profile, 12, Color.WHITE,
new Intent(this, ProfileActivity.class)
));
return indicators;
}
}
在 res/drawable 準備兩套圖標(默認/選中狀態),在 strings.xml 定義標題文案,將對應的目標 Activity 類傳入 IndicatorInfo 構造器。框架會自動處理底部欄渲染、點擊事件分發及頁面切換動畫。
若專案已遷移至 AndroidX,強烈建議使用 BottomNavigationView(Material Design 組件)配合 Navigation Component 實現:
無論採用哪種方案,核心原則都是:將導航邏輯與業務邏輯解耦,讓開發者專注於核心功能實現。