架構模式
MainActivity (單 Activity)
├── DrawerLayout (根佈局)
│ ├── FrameLayout (內容容器) ← Fragment 替換目標
│ └── NavigationView (側滑菜單) ← 菜單項點擊監聽
└── 多個 Fragment (頁面內容)
核心實現
// MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var drawerLayout: DrawerLayout
private lateinit var navView: NavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
drawerLayout = findViewById(R.id.drawerLayout)
navView = findViewById(R.id.navView)
// 設置菜單項點擊監聽
navView.setNavigationItemSelectedListener { item ->
val fragment = when (item.itemId) {
R.id.nav_home -> HomeFragment()
R.id.nav_profile -> ProfileFragment()
R.id.nav_settings -> SettingsFragment()
else -> HomeFragment()
}
switchFragment(fragment)
item.isChecked = true
drawerLayout.closeDrawers()
true
}
// 默認顯示首頁
if (savedInstanceState == null) {
switchFragment(HomeFragment())
navView.menu.getItem(0).isChecked = true
}
}
private fun switchFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.replace(R.id.contentFrame, fragment)
.commit()
}
}
佈局文件
菜單資源
進階:狀態保持與性能優化
| 需求 | 方案 |
| Fragment 狀態保持 | 使用 `FragmentTransaction.add()` + `show()/hide()` 替代 `replace()`,或配合 `ViewModel` 存儲數據 |
| 避免重複創建 | 用 `FragmentManager.findFragmentByTag()` 復用實例 |
| 返回鍵處理 | 重寫 `onBackPressed()`:抽屜打開時關閉,否則退出/返回棧 |
| 深層鏈接 | 配合 `Navigation Component` 實現圖導航 |
現代替代:Navigation Component
// navigation_graph.xml
// Activity
val navController = findNavController(R.id.navHostFragment)
navView.setupWithNavController(navController) // 自動綁定菜單點擊
總結
側滑欄導航 = **DrawerLayout + NavigationView + Fragment 替換**。每個菜單項對應一個 Fragment,點擊時 `replace()` 容器內容。**不創建新 Activity**,單 Activity 承載所有頁面,符合現代 Android 架構指南。
- 上一篇文章: VS2013 scanf_s 緩衝區大小參數缺失導致結構體輸入跳過:C11 安全函數正確用法詳解
- 下一篇文章: C語言表達式運算結果存儲位置:編譯器決定而非語言規定,寄存器與內存的動態分配機制
Copyright ©
程式碼之家 All Rights Reserved