Android启动屏不识别?attr/main_background,明暗模式适配失败求助
问题原因
你遇到的?attr/main_background在启动页layer-list中无效的核心原因是:Drawable属于静态资源,在加载阶段无法动态解析主题中的属性引用。
启动页的windowBackground是App进程刚启动时就被系统加载的,此时Activity的主题上下文还未完全初始化,静态Drawable只能识别固定的颜色、图片等资源,无法解析依赖主题动态赋值的?attr属性——硬编码颜色能正常生效,正是因为它是静态固定值,不需要主题上下文参与解析。
解决方案
这里提供两种业界常用的适配明暗主题的方案:
方案1:为明暗主题分别创建同名Layer-list
利用Android资源目录的-night后缀特性,为浅色、深色主题分别创建对应的启动页背景Drawable:
- 在
res/drawable/下创建默认(浅色)的splash_background.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/main_background_light" /> <item> <bitmap android:gravity="center" android:src="@drawable/ic_launcher" /> </item> </layer-list>
- 在
res/drawable-night/下创建同名的splash_background.xml(深色主题生效):
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/main_background_dark" /> <item> <bitmap android:gravity="center" android:src="@drawable/ic_launcher" /> </item> </layer-list>
保持你原本的SplashTheme和Activity配置不变,系统会自动根据当前明暗模式加载对应目录下的Drawable资源。
方案2:在主题中为明暗模式分别配置windowBackground
如果想减少Drawable文件的重复,可以把启动页背景的配置放到主题中,利用主题的-night目录特性:
- 在
res/values/styles.xml(浅色主题)中定义SplashTheme:
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar"> <item name="android:windowBackground">@drawable/splash_background_light</item> </style>
- 在
res/values-night/styles.xml(深色主题)中覆盖SplashTheme的配置:
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar"> <item name="android:windowBackground">@drawable/splash_background_dark</item> </style>
其中splash_background_light和splash_background_dark可以复用同一个图标Drawable,比如把图标单独提取为res/drawable/splash_icon.xml:
<item xmlns:android="http://schemas.android.com/apk/res/android"> <bitmap android:gravity="center" android:src="@drawable/ic_launcher" /> </item>
然后在两个背景Drawable中引用:
<!-- splash_background_light.xml --> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/main_background_light" /> <item android:drawable="@drawable/splash_icon" /> </layer-list>
这样既避免了代码重复,又能实现明暗主题的适配。
内容的提问来源于stack exchange,提问作者Pavel Poley
相关产品推荐
相关产品推荐

