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

Android中Bottom Navigation结合Navigation Component的重选返回需求

实现重新点击BottomNavigationItem返回对应Fragment根页面

直接通过监听BottomNavigationView的重新选中事件来实现需求,无需修改原有导航关联逻辑:

val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragment) as NavHostFragment
val navController = navHostFragment.navController

val bottomNavBar = findViewById<BottomNavigationView>(R.id.bottomBar)
setupWithNavController(bottomNavBar, navController)

// 监听重新选中已激活的BottomNavigationItem
bottomNavBar.setOnItemReselectedListener { item ->
    // 替换为你第二个Fragment对应的menu item ID
    val targetRootId = R.id.fragment_two
    if (item.itemId == targetRootId) {
        // 弹出导航栈中所有位于目标Fragment之上的页面,回到目标Fragment
        val isPopped = navController.popBackStack(targetRootId, false)
        // 可选:如果当前已经在目标Fragment,执行刷新等额外操作
        if (!isPopped) {
            // 示例:(targetRootId对应的Fragment as? SecondFragment)?.refreshContent()
        }
    }
}

逻辑说明

  • setOnItemReselectedListener仅在用户点击当前已选中的导航项时触发,完全匹配“再次点击第二个图标”的场景。
  • popBackStack(targetRootId, false)会保留targetRootId对应的Fragment,弹出所有在它之后入栈的子Fragment,精准回到第二个Fragment的内容页。
  • 如果当前已经处于第二个Fragment,popBackStack会返回false,此时可根据需求添加页面刷新等自定义逻辑。

内容的提问来源于stack exchange,提问作者Purab Modi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:27:30