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

Compose项目中Splash Screen自定义图片背景显示黑色问题求助

解决androidx.core:core-splashscreen:1.0.1图片背景显示黑色的问题

完全可以实现以图片为背景的启动页,你遇到的黑色背景问题是由于配置流程有误导致的,以下是正确的实现步骤及排查方案:

1. 确保图片资源有效

  • 将splash图片放在正确的drawable资源目录(如drawable/、drawable-xhdpi/等),确认图片文件无损坏,且尺寸适配主流设备屏幕。
  • 支持PNG、WEBP等常见格式,带透明通道的图片也可正常使用。

2. 正确配置启动页主题

Theme.App.Starting必须继承Theme.SplashScreen主题,而非应用的常规主题,示例配置如下:

<style name="Theme.App.Starting" parent="Theme.SplashScreen">
    <!-- 设置启动页背景图片 -->
    <item name="windowSplashScreenBackground">@drawable/splash</item>
    <!-- 可选:配置启动图标(无需图标可删除此属性) -->
    <item name="windowSplashScreenAnimatedIcon">@drawable/ic_launcher_foreground</item>
    <!-- 指定启动页结束后切换到的应用主题 -->
    <item name="postSplashScreenTheme">@style/Theme.App</item>
</style>

3. 在Manifest中绑定启动页主题

给启动Activity指定android:theme="@style/Theme.App.Starting",示例:

<activity
    android:name=".MainActivity"
    android:exported="true"
    android:theme="@style/Theme.App.Starting">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

4. 在Compose中完成启动页过渡逻辑

在启动Activity的onCreate方法中,必须调用installSplashScreen(),并设置保持启动页显示的条件,直到应用内容加载完成:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化启动屏
        val splashScreen = installSplashScreen()
        
        // 模拟内容加载(替换为你的实际加载逻辑,如数据请求、初始化操作)
        var isContentLoaded by remember { mutableStateOf(false) }
        LaunchedEffect(Unit) {
            // 模拟加载延迟
            delay(2000)
            isContentLoaded = true
        }
        
        // 保持启动屏显示直到内容加载完成
        splashScreen.setKeepOnScreenCondition { !isContentLoaded }
        
        setContent {
            AppTheme {
                if (isContentLoaded) {
                    // 加载完成后显示应用主内容
                    MainContent()
                }
            }
        }
    }
}

常见问题排查

  • 若仍显示黑色背景,检查图片是否被系统压缩或格式不兼容:可尝试转换为WEBP格式,或调整图片尺寸适配屏幕。
  • 确认Theme.App.Starting的父主题是Theme.SplashScreen,而非应用的常规主题。
  • 检查启动Activity中是否调用了installSplashScreen(),未调用此方法会导致启动屏不生效,显示默认黑色背景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:27:13