前言:
这是翻译的一篇文章,How to Create a Splash Screen。
这篇文章里,作者提出了一个很独特的实现闪屏的方案,代码也验证过,确实可行。现在,我们按照他的方案,一步一步来实现。
ps:不习惯于一字一译,这样有时候会很生硬,所以我采用的是按照自己的理解,融合作者和自己想表达的意思翻译而来。目的也只是为了让文章既能好读,也能好懂。
所谓Spalsh页面(闪屏页面)一般就是在app启动的时候,展示公司的logo或是name(当然,国内的app 可能不是这么简单的玩下)。
我们实现闪屏可能有很多种方案,比如创建一个SplashActivity, 用一个计时器,几秒之后跳转MainActivity,如果仅仅是展示一张图片,有时候就没必要这样做了,完全可以不通过创建单独的Activity,而是利用app的theme来实现。
实现:
1. 创建一个drawable,包含app logo 和背景色
//drawable/splash.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#ff445e"/>
<item android:drawable="@drawable/test"
android:gravity="center"/>
</layer-list>
2. 创建splash 要用到的主题样式
//themes.xml
<!-- Splash Screen theme. -->
<style name="splashScreenExampleTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Drawable resource file is specified as the window background -->
<item name="android:windowBackground">@drawable/spalsh</item>
<!-- Set the color of the status bar -->
<item name="android:statusBarColor">@color/black</item>
</style>
3. 将主题样式应用到Application 中
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:name=".MyApp"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/splashScreenExampleTheme">
4. MainActivity设回Activity默认样式
//MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.Theme_TestApril)
super.onCreate(savedInstanceState)
}
以上就是不用额外创建SplashActivity, 而是采用theme样式来达到同样的效果,感兴趣的可以试试
优缺点:
优点:
简便、快捷
缺点:
1 适用面狭窄:众所周知,国内app的Splash页面总是要玩出一朵花出来,而不是简简单单一个图片样式。
2.其他页面记得把样式设回默认的activity样式,虽然可以在base页面统一处理,但是还是多做了一步操作。