Android夜间主题下ActionBar颜色始终为黑色该如何解决?
问题原因
你使用的深色主题父主题Theme.MaterialComponents.DayNight.DarkActionBar在夜间模式下有默认的ActionBar样式覆盖,会优先使用主题surface色作为ActionBar背景,导致你配置的colorPrimary不生效。
可行解决方案
方案1:显式指定ActionBar样式(改动最小)
直接在现有深色主题的style标签内新增一行配置,强制指定ActionBar背景色:
<item name="android:actionBarBackground">@color/purple_500</item>
如果需要同时修改ActionBar上的文字、图标颜色,再加以下配置:
<item name="actionBarTheme">@style/Widget.MyApp.ActionBar</item>
然后在同个themes.xml文件里新增自定义样式:
<style name="Widget.MyApp.ActionBar" parent="Widget.MaterialComponents.ActionBar.Solid"> <item name="colorPrimary">@color/purple_500</item> <item name="colorOnPrimary">@color/black</item> </style>
方案2:使用自定义Toolbar(官方推荐)
把两个日夜主题的父主题都替换为Theme.MaterialComponents.DayNight.NoActionBar,之后在页面布局中主动添加Toolbar组件,直接给Toolbar设置背景色为?attr/colorPrimary即可,这种方式不会受默认主题样式覆盖,自定义灵活性更高。
注意事项
- 确认深色主题的
themes.xml存放在res/values-night目录下,不要和日间主题放混 - 测试时确认应用已经切换到夜间模式,避免误加载日间主题配置
内容的提问来源于stack exchange,提问作者Jeff L
相关产品推荐
相关产品推荐

