Android中Bottom Navigation结合Navigation Component的重选返回需求
直接通过监听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
相关产品推荐
相关产品推荐

