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

Android SplashScreen API与AppCompatActivity及Material Theme兼容问题求助

解决方案:AppCompatActivity + Material Theme 集成 SplashScreen API

1. 确认依赖版本

使用androidx.core:core-splashscreen 1.0.0及以上版本,该版本已修复与AppCompatActivity的兼容问题。在模块的build.gradle或build.gradle.kts中添加依赖:

dependencies {
    implementation "androidx.core:core-splashscreen:1.0.1"
}

2. 配置主题层级

  • 启动主题:继承Theme.SplashScreen,仅配置SplashScreen相关属性,并指定postSplashScreenTheme为你的Material主题:
    <!-- res/values/themes.xml -->
    <style name="Theme.App.Start" parent="Theme.SplashScreen">
        <item name="windowSplashScreenBackground">@color/splash_background</item>
        <item name="windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
        <item name="windowSplashScreenAnimationDuration">300</item>
        <item name="postSplashScreenTheme">@style/Theme.App.Material</item>
    </style>
    
  • Material主题:继承Theme.MaterialComponents.DayNight(或对应变体),配置业务所需的Material属性:
    <style name="Theme.App.Material" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryVariant">@color/primary_variant</item>
        <item name="colorSecondary">@color/secondary</item>
        <!-- 其他Material主题配置 -->
    </style>
    

3. 在AppCompatActivity中初始化SplashScreen

在主Activity的onCreate方法中,先调用installSplashScreen(),再执行super.onCreate和setContentView:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // 初始化SplashScreen
        val splashScreen = installSplashScreen()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 可选:若需等待数据加载再隐藏SplashScreen,设置保持显示条件
        splashScreen.setKeepOnScreenCondition {
            // 返回true保持显示,false则自动隐藏
            viewModel.isDataLoaded.value != true
        }
    }
}

4. 修正Manifest配置

将主Activity的android:theme设置为SplashScreen启动主题:

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

5. 常见问题排查

  • 检查是否有代码(如setTheme)覆盖了Manifest中的主题设置;
  • 确保Material主题继承自Theme.MaterialComponents系列,而非旧版Theme.Material;
  • 不要在启动主题中配置Material专属属性,所有Material相关设置放在postSplashScreenTheme指定的主题内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 21:37:28