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

求助:按下返回按钮时Bottom Navigation Bar图标颜色未更新

问题解决:返回Activity时底部导航图标颜色不更新

你的核心问题是所有Activity都固定将底部导航的选中项设为R.id.home,导致无论当前处于哪个页面,底部导航始终高亮Home项。当你从其他页面返回前一个Activity时,前一个页面的底部导航依然保持Home选中状态,自然看不到颜色变化。

解决方案

1. 为每个Activity设置对应页面的选中项

每个页面需要根据自身功能,将底部导航的选中项设置为对应的菜单项ID:

  • HomeActivity:bottom_navigation.selectedItemId = R.id.home
  • SellActivity:bottom_navigation.selectedItemId = R.id.sell
  • ChatActivity:bottom_navigation.selectedItemId = R.id.chat
  • ProfileActivity:bottom_navigation.selectedItemId = R.id.profile

2. 在onResume()中设置选中状态(关键)

Activity从后台恢复(比如按返回键回到页面)时,onCreate()不会重新执行,因此需要把设置选中项的代码放到onResume()方法中,确保每次页面显示时都能正确高亮对应项。

以ChatActivity为例,修改后的代码如下:

override fun onResume() {
    super.onResume()
    bottom_navigation.selectedItemId = R.id.chat
}

bottom_navigation.setOnNavigationItemSelectedListener {
    when (it.itemId){
        R.id.home -> {
            startActivity(Intent(this, HomeActivity::class.java))
            overridePendingTransition(0,0)
            true
        }
        R.id.sell -> {
            startActivity(Intent(this, SellActivity::class.java))
            overridePendingTransition(0,0)
            true
        }
        R.id.chat -> {
            // 当前已在ChatActivity,无需重复跳转
            true
        }
        R.id.profile -> {
            startActivity(Intent(this, ProfileActivity::class.java))
            overridePendingTransition(0,0)
            true
        }
        else -> false
    }
}

额外优化

在导航项的点击事件中,当前页面对应的项不需要执行跳转逻辑,避免重复打开同一个Activity,提升体验。

原理说明

每个Activity是独立的组件,它们的底部导航状态互不共享。只有在每个页面显示时,主动设置对应菜单项为选中状态,才能让Selector的state_checked状态生效,从而切换图标颜色。当你按返回键回到前一个Activity时,onResume()方法会触发,重新设置选中项,底部导航的颜色就会正确更新。

内容的提问来源于stack exchange,提问作者Divyansh Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:07:11