如何在应用启动图标中使用M3动态色彩?
实现启动图标使用M3主题属性色彩的方法
方法1:通过自适应图标Foreground的Tint实现
- 调整前景图标(
ic_launcher_foreground.xml)的路径填充色为纯色(比如白色#FFFFFFFF),不要直接使用?attr/属性:
<!-- res/drawable/ic_launcher_foreground.xml --> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"> <path android:fillColor="#FFFFFFFF" android:pathData="..." /> <!-- 替换为你的图标路径 --> </vector>
- 在自适应图标配置文件(
res/mipmap-anydpi-v26/ic_launcher.xml)中,给foreground节点添加tint和tintMode属性:
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <background android:drawable="@color/ic_launcher_background" /> <foreground android:drawable="@drawable/ic_launcher_foreground" android:tint="?attr/colorPrimary" android:tintMode="src_in" /> </adaptive-icon>
src_in模式会让主题色覆盖前景图标的非透明区域,完美适配动态主题色彩。
方法2:使用Color Selector引用主题属性
- 创建颜色选择器文件
res/color/icon_primary_tint.xml,直接引用M3主题属性:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="?attr/colorPrimary" /> </selector>
- 在前景图标的vector文件中,将
fillColor指向这个颜色选择器:
<!-- res/drawable/ic_launcher_foreground.xml --> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108"> <path android:fillColor="@color/icon_primary_tint" android:pathData="..." /> <!-- 替换为你的图标路径 --> </vector>
- 正常将前景图标引用到自适应图标配置中即可:
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <background android:drawable="@color/ic_launcher_background" /> <foreground android:drawable="@drawable/ic_launcher_foreground" /> </adaptive-icon>
关键注意事项
- 确保应用主题已正确配置M3样式(比如
Theme.Material3.DayNight.NoActionBar),且colorPrimary属性已在主题中定义。 - 不要直接在vector的
fillColor中写?attr/colorPrimary,Launcher加载图标时无法直接解析该属性,这就是你之前图标空白的原因。 - 部分第三方Launcher可能不支持动态主题色启动图标,但系统默认Launcher(如Pixel Launcher、原生Android Launcher)会和系统设置应用表现一致,支持该功能。
内容的提问来源于stack exchange,提问作者Sujit
相关产品推荐
相关产品推荐

