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

如何在XML布局中设置Material Design 3的surface+x%primary颜色?

在XML布局中使用Material Design 3的Surface+Primary色调颜色

直接引用主题内置属性

Material Design 3的主题已预设对应颜色的属性,可直接在XML中调用:

  • Surface 2 对应 ?attr/colorSurfaceVariant
  • Surface 3 对应 ?attr/colorSurfaceDim
  • 基础Surface(Surface 1)对应 ?attr/colorSurface

示例代码:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/colorSurfaceVariant" />

自定义颜色资源(精确匹配代码中的SurfaceColors)

若需要和代码里SurfaceColors.SURFACE_2.getColor(this)完全一致的颜色值,可按以下步骤操作:

  1. 在代码中临时打印颜色的十六进制值:
int surface2Color = SurfaceColors.SURFACE_2.getColor(this);
Log.d("SurfaceColorHex", String.format("#%06X", (0xFFFFFF & surface2Color)));
  1. 将打印出的十六进制值添加到res/values/colors.xml:
<color name="surface_2">#打印出的十六进制值</color>
  1. 在XML布局中引用自定义颜色:
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/surface_2" />

全局主题覆盖

如果要统一修改应用内的Surface色调颜色,可在主题样式中自定义属性:

<style name="YourAppTheme" parent="Theme.Material3.DayNight">
    <item name="colorSurfaceVariant">@color/your_custom_surface_2</item>
</style>

之后所有引用?attr/colorSurfaceVariant的控件都会自动使用你设置的颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:01:23