如何在Jetpack Compose启动页资源中使用主题背景色?
如何在启动页XML中使用Jetpack Compose Material主题背景色适配明暗模式
你无法直接在XML资源中引用MaterialTheme.colorScheme.background,因为XML资源系统无法访问Compose运行时的主题对象。不过有两种可行方案来实现启动页背景与Compose Material主题同步适配明暗模式:
方案一:通过颜色资源关联(推荐)
这种方式让XML启动页和Compose主题共用同一套颜色资源,自动适配明暗模式:
创建明暗模式对应的颜色资源
- 在
res/values/colors.xml中定义亮模式背景色:<color name="splash_background">#FFFFFF</color> - 在
res/values-night/colors.xml中定义暗模式背景色:<color name="splash_background">#121212</color>
这里的颜色值要和你Compose Material主题中
background的颜色保持一致。- 在
让Compose主题引用该颜色资源
在你的Compose主题配置中,直接使用这个颜色资源来定义background:@Composable fun AppTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colorScheme = if (darkTheme) { darkColorScheme( background = colorResource(id = R.color.splash_background) ) } else { lightColorScheme( background = colorResource(id = R.color.splash_background) ) } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }修改启动页XML使用该颜色资源
把原来硬编码的@color/white替换成@color/splash_background:<?xml version="1.0" encoding="utf-8"?> <resources> <style name="Theme.App.Starting" parent="Theme.SplashScreen"> <item name="windowSplashScreenBackground">@color/splash_background</item> <item name="windowSplashScreenAnimatedIcon">@drawable/ic_baseline_compress_24</item> <item name="postSplashScreenTheme">@style/Theme.DailyTasks</item> </style> </resources>
方案二:代码动态设置背景(适用于动态主题场景)
如果你的Compose主题背景色是动态生成的(比如用户自定义颜色),可以通过代码在启动页加载时动态修改背景:
- 在启动Activity中配置SplashScreen
注意:需要确保在获取class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 初始化Compose主题(确保能获取到colorScheme) setContent { AppTheme { // 这里可以先占位,后续加载实际内容 Box(modifier = Modifier.fillMaxSize()) } } // 动态设置启动页背景 installSplashScreen().setOnExitAnimationListener { splashScreenView -> // 获取当前Compose主题的背景色 val backgroundColor = MaterialTheme.colorScheme.background.toArgb() // 修改启动页背景 splashScreenView.view.setBackgroundColor(backgroundColor) // 执行退出动画(可选) splashScreenView.animate() .alpha(0f) .setDuration(500) .withEndAction { splashScreenView.remove() } } } }MaterialTheme.colorScheme时,Compose环境已经初始化完成。
内容的提问来源于stack exchange,提问作者Vilmar Cabañero
相关产品推荐
相关产品推荐

