Splash Screen Api Usage

51 阅读1分钟

Gif_20240131_173402.gif

  • 实现步骤
  1. 引用库 implementation("androidx.core:core-splashscreen:1.0.0")
  2. 定义一个主题,parent主题是 Theme.Splash
<style name="Theme.App.Starting" parent="Theme.SplashScreen">
   <!-- 设置 splash screen 的背景, 动画 icon, 和 动画时长. -->
   <item name="windowSplashScreenBackground">@color/white</item>

   <!-- 使用 windowSplashScreenAnimatedIcon属性 添加一个drawable 或者一个 animated
        drawable,必须要有两者其一 -->
   <item name="windowSplashScreenAnimatedIcon">@drawable/yourSplashIcon</item>
   <!-- 若添加了 animated icons,此属性必须配合使用 -->
   <item name="windowSplashScreenAnimationDuration">200</item>

   <!-- 设置 启动之后的 activity 的主题 必须设置项 -->
   <item name="postSplashScreenTheme">@style/Theme.App</item>
</style>
  1. 在AndroidManifest.xml文件中的配置
<manifest>
   <application android:theme="@style/Theme.App.Starting">
    <!-- 或者 -->
        <activity android:theme="@style/Theme.App.Starting">

可以在 application标签设置,也可以在 指定的启动Activity,比如MainActivity的theme属性中设置。

需要注意在application标签注册会影响到所有activity,看项目需要配置。

  1. 在启动activity的 super.onCreate() 前调用 installSplashScreen() 方法
class MainActivity : AppCompatActivity() {
    private val binding : ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
   override fun onCreate(savedInstanceState: Bundle?) {
       // Handle the splash screen transition.
       val splashScreen = installSplashScreen()

       super.onCreate(savedInstanceState)
       setContentView(binding.root)
    }
 }   

方法返回的 splashScreen 对象,可以用来控制闪屏的展示时间,和定制动画效果。

  1. splashScreen 对象 控制展示时长 ,splashScreen对象有两个控制展示的方法可以设置,官方文档使用
splashScreen.setKeepOnScreenCondition(object :SplashScreen.KeepOnScreenCondition{  
    override fun shouldKeepOnScreen(): Boolean {  
        //返回false 结束闪屏展示,返回true保持展示
  
        return false  
    }  
})
// 此方法内部实现在 ViewTreeObserver.OnPreDrawListener 回调中
//也可参照官方链接中类似方法实现

以上方式可以自己设定一个定时器,控制liveData或者Flow更新boolean 值结束展示。

splashScreen.setOnExitAnimationListener {  splashScreenViewProvider ->
    val view = splashScreenViewProvider.view  
  
    val slideUp = ObjectAnimator.ofFloat(  
        view,  
        View.TRANSLATION_Y,  
        0f,  
        -view.height.toFloat()  
    )  
    slideUp.interpolator = AnticipateInterpolator()  
    slideUp.duration = delay  
  
    slideUp.doOnEnd { splashScreenViewProvider.remove() }  
  
    slideUp.start()
}

以上方式也可以直接Coroutine协程里delay一段时间,使用 remove()方法移除闪屏。具体实现看项目需要。

代码demo gitee