BottomNavigationView动态主题颜色不更新及选中动画咨询
问题解决方案
一、BottomNavigationView 不跟随动态取色问题
这个问题是依赖版本适配+属性配置错误共同导致的,按以下步骤修复即可:
- 升级Material依赖版本:你当前使用的
com.google.android.material:material:1.6.1存在BottomNavigationView动态色适配的已知bug,直接升级到1.9.0及以上稳定版本即可解决大部分适配问题。 - 检查布局与主题配置:
- 删掉布局中BottomNavigationView上手动设置的
android:background属性,不要给它硬编码任何背景色/背景drawable,组件默认会读取主题的?attr/colorSurface作为背景,动态取色框架会自动更新该属性值。 - 检查
themes.xml中是否自定义了bottomNavigationStyle,如果自定义style中写死了背景色,替换为?attr/colorSurface主题属性即可。 - 如果要适配动态取色,建议将应用基础主题切换为
Theme.Material3.DayNight,M2主题对动态取色的组件覆盖不全。
- 删掉布局中BottomNavigationView上手动设置的
- 兜底方案:如果以上操作后仍未生效,可以在Activity的
onCreate方法中手动给组件应用动态色:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BottomNavigationView navView = findViewById(R.id.bottom_navigation); DynamicColors.applyToView(navView, getTheme()); }
二、选中项弹性动画实现
Google通讯录的弹性选中效果是Material组件库官方自带的效果,不需要自定义动画,按以下配置即可:
- 确保Material依赖版本在1.7.0及以上(升级依赖步骤同上)
- 在布局的BottomNavigationView节点中添加两个属性:
<com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottom_navigation" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:menu="@menu/bottom_nav_menu" <!-- 新增以下两个属性 --> app:labelVisibilityMode="selected" app:itemActiveIndicatorStyle="@style/Widget.Material3.BottomNavigationView.ActiveIndicator.Elastic" />
- 如果需要调整弹性幅度、缩放比例,可以自定义选中指示器样式:
<style name="CustomElasticIndicator" parent="Widget.Material3.BottomNavigationView.ActiveIndicator.Elastic"> <!-- 选中时图标缩放比例,默认1.2倍 --> <item name="android:scaleX">1.15</item> <item name="android:scaleY">1.15</item> <!-- 动画时长,默认300ms --> <item name="android:duration">250</item> </style>
之后把布局中app:itemActiveIndicatorStyle的值替换为你自定义的style即可,效果和Google通讯录完全一致。
内容的提问来源于stack exchange,提问作者backslashV
相关产品推荐
相关产品推荐

