BottomNavigationView动态设置背景色仅onResume生效如何解决
解决方案
- 优先清除BottomNavigationView默认的背景着色(tint):Material组件默认自带
backgroundTint属性,会覆盖你手动设置的background drawable,设置背景色前先清空tint即可:
// 先清空背景着色列表 binding.bottomNav.root.backgroundTintList = null // 再设置背景色 binding.bottomNav.root.background = ColorDrawable(Color.parseColor(primary.uppercase()))
- 确认UI更新逻辑在主线程执行:如果你的API请求回调默认执行在子线程,直接操作UI不会触发即时重绘,只有下次页面回到前台触发系统重绘时才会生效,需要把UI更新逻辑切到主线程:
runOnUiThread { binding.bottomNav.root.backgroundTintList = null binding.bottomNav.root.setBackgroundColor(Color.parseColor(primary.uppercase())) }
- 推荐使用官方原生方法设置背景色:Material 1.1.0及以上版本的BottomNavigationView,直接调用
setBackgroundColor()方法比手动创建ColorDrawable替换background兼容性更好,不需要额外处理drawable的重绘逻辑。
如果修改后还是不生效,可以检查布局XML中是否给BottomNavigationView硬编码了backgroundTint、background属性,或者父布局是否有动画/过渡效果延迟了控件重绘
内容的提问来源于stack exchange,提问作者Patty P
相关产品推荐
相关产品推荐

