首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 側滑欄導航多頁面:NavigationView + Fragment 替換實現單 Activity 多頁面架構

     編輯:程式設計綜合問答

架構模式


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()
    }
}

佈局文件




    
    
    
    
    
    

菜單資源




    
        
        
        
    

進階:狀態保持與性能優化

現代替代:Navigation Component


// navigation_graph.xml

    
    


// Activity
val navController = findNavController(R.id.navHostFragment)
navView.setupWithNavController(navController)  // 自動綁定菜單點擊

總結

側滑欄導航 = **DrawerLayout + NavigationView + Fragment 替換**。每個菜單項對應一個 Fragment,點擊時 `replace()` 容器內容。**不創建新 Activity**,單 Activity 承載所有頁面,符合現代 Android 架構指南。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
需求方案
Fragment 狀態保持使用 `FragmentTransaction.add()` + `show()/hide()` 替代 `replace()`,或配合 `ViewModel` 存儲數據
避免重複創建用 `FragmentManager.findFragmentByTag()` 復用實例
返回鍵處理重寫 `onBackPressed()`:抽屜打開時關閉,否則退出/返回棧
深層鏈接配合 `Navigation Component` 實現圖導航