You need to enable JavaScript to run this app. 深色模式下使用Material PrimarySurface样式如何获取Toolbar elevation效果
优惠活动
大模型
产品
解决方案
定价
更多

深色模式下使用Material PrimarySurface样式如何获取Toolbar elevation效果

解决方案

你遇到的elevation不生效问题是因为没有开启Material Components的深色模式 elevation 叠加特性,按以下步骤调整即可用官方原生方式实现效果,无需手动指定背景色:

  1. 开启elevation叠加开关
    在你的AppTheme中新增显式配置,开启深色模式下的表面高度叠加效果:
<style name="AppTheme" parent="LightCustomFontStyle">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryVariant">@color/colorPrimaryDark</item>
    <item name="colorSecondary">@color/colorAccent</item>
    <!-- 新增:开启深色模式elevation叠加 -->
    <item name="elevationOverlayEnabled">true</item>
    <item name="toolbarStyle">@style/toolbarStyle</item>
</style>
  1. 给Toolbar配置正确的高度属性
    有两种配置方式任选其一即可:
  • 方式一:直接在style中固定Toolbar高度
<style name="toolbarStyle" parent="Widget.MaterialComponents.Toolbar.PrimarySurface">
    <item name="elevation">4dp</item>
</style>
  • 方式二:在布局文件中给Toolbar节点添加属性app:elevation="4dp",注意不要用android:elevation,要使用Material Components的自定义属性前缀app。
  1. 检查Activity根布局配置
    确保你的Activity根布局背景设置为?attr/colorBackground,不要硬编码写死#121212,确保系统可以正确区分页面背景和Toolbar的表面层级。

如果调整后还是没有效果,可以检查你的AppTheme父主题是否继承自Theme.MaterialComponents.DayNight的派生系列,只有Material Components主题才自带elevation叠加特性,传统AppCompat主题不支持该效果。如果确实无法切换父主题,再考虑手动给values-night下的colors.xml定义一个更浅的Toolbar专用背景色即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 03:54:04