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

如何在Android Studio中通过导航抽屉切换Activity

如何在导航抽屉点击菜单项时打开新Activity

没问题,既然你暂时不想接触Fragment,只想通过点击导航抽屉的菜单项来打开对应的Activity,我来帮你修改现有代码。你的基础框架已经搭好了,只需要在菜单选择的回调里添加判断菜单项ID并启动对应Activity的逻辑即可。

先看你现有的基础代码:

mDrawerLayout = findViewById(R.id.drawer_layout)
val navigationView: NavigationView = findViewById(R.id.nav_view)
navigationView.setNavigationItemSelectedListener { menuItem ->
    // set item as selected to persist highlight
    menuItem.isChecked = true
    // close drawer when item is tapped
    mDrawerLayout.closeDrawers()
    // Add code here to update the UI based on the item selected
    // For example, swap UI fragments here
    true
}

修改方案

我们需要在回调里,根据menuItem.itemId区分不同的菜单项,然后创建Intent启动对应的Activity。假设你的导航菜单(一般在res/menu/nav_menu.xml中)给每个菜单项都设置了唯一的android:id,对应你的10个Activity,修改后的完整代码如下:

mDrawerLayout = findViewById(R.id.drawer_layout)
val navigationView: NavigationView = findViewById(R.id.nav_view)
navigationView.setNavigationItemSelectedListener { menuItem ->
    // 保留原有选中和关闭抽屉的逻辑
    menuItem.isChecked = true
    mDrawerLayout.closeDrawers()

    // 根据菜单项ID匹配对应Activity并启动
    when (menuItem.itemId) {
        R.id.nav_home -> {
            startActivity(Intent(this, HomeActivity::class.java))
        }
        R.id.nav_profile -> {
            startActivity(Intent(this, ProfileActivity::class.java))
        }
        R.id.nav_settings -> {
            startActivity(Intent(this, SettingsActivity::class.java))
        }
        // 按照这个格式,继续添加剩下7个菜单项的判断逻辑
        R.id.nav_notes -> {
            startActivity(Intent(this, NotesActivity::class.java))
        }
        // ... 其他Activity的匹配代码
    }

    true
}

注意事项

  • 请把代码里的HomeActivity、ProfileActivity等替换成你实际的Activity类名,R.id.nav_home替换成菜单文件中对应的菜单项ID。
  • 如果你的代码是在Fragment中实现的,需要把this替换成requireContext()或者activity。
  • 若需要调整Activity的启动模式(比如避免重复创建实例),可以给Intent添加标记,比如intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK),默认启动模式一般能满足基础需求。

内容的提问来源于stack exchange,提问作者Keith Colclough

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:00:39