You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Nav Controller切换Fragment?Navigation Drawer导航失效求助

问题排查与解决

核心问题

你代码里的冲突导致导航失效:同时使用了navView.setupWithNavController()和自定义的setNavigationItemSelectedListener,后者覆盖了前者的默认导航逻辑,点击菜单时只执行关闭抽屉的操作,没有触发页面导航。

解决步骤

  • 移除自定义导航选中监听器:setupWithNavController已经内置了「导航到对应Fragment + 关闭抽屉」的完整逻辑,不需要额外设置setNavigationItemSelectedListener。删除这段冗余代码:
    navView.setNavigationItemSelectedListener{
        when (it.itemId) {
            R.id.nav_dashboard -> {
                drawer.closeDrawer(GravityCompat.START)
            }
            R.id.nav_profile -> {
                drawer.closeDrawer(GravityCompat.START)
            }
        }
        true
    }
    
  • 校验ID匹配关系:确保导航菜单(res/menu/nav_menu.xml)里的item id,和导航图(res/navigation/nav_graph.xml)中对应Fragment的id完全一致。比如:
    • 菜单中Dashboard的item id应为R.id.dashboardFragment,而非R.id.nav_dashboard
    • 菜单中Profile的item id应为R.id.profileFragment,而非R.id.nav_profile

修正后的完整代码示例

val navHostFragment = supportFragmentManager.findFragmentById(R.id.container) as NavHostFragment
navController = navHostFragment.navController
val navView: NavigationView = findViewById(R.id.nav_view)
appBarConfiguration = AppBarConfiguration(
    setOf(
        R.id.dashboardFragment,
        R.id.profileFragment,
    ), drawerLayout
)
setupActionBarWithNavController(navController!!, appBarConfiguration!!)
navView.setupWithNavController(navController!!) 

内容的提问来源于stack exchange,提问作者Nain Malik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:05:17