設計一個啓動頁的兩種方式
app 越來越複雜,主頁啓動越來越耗時,並且往往需要預加載數據,這時候先展示一個啓動頁就顯得十分有必要了。流行的 app 一般都採用這種做法。
我們知道,如果第一屏啓動的慢,那麼會默認展示一個黑屏的缺省頁,這個黑色是默認的 windowBackground 的顏色,許多啓動優化的操作裏,會修改 windowBackground 默認展示一張啓動圖片。
更改啓動背景
爲了不和默認主題混淆,首先需要聲明一個啓動主題,只設置給啓動頁:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<!-- 啓動頁主題-->
<style name="AppTheme.Splash" parent="AppTheme">
<item name="android:windowBackground">@drawable/splash_drawable</item>
</style>
啓動頁一般是顯示一個 logo ,下面使用 layer-list 描繪出啓動頁佈局 splash_drawable :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/colorWhite" />
<item>
<bitmap
android:gravity="center"
android:src="@drawable/ic_zhanweifu"></bitmap>
</item>
</layer-list>
然後設置給主頁:
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme.Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
啓動應用,會看到先看到 splash_drawable 而不是原來默認的黑屏 ,但是 MainActivity 的 背景也和 splash_drawable 一樣了。 因爲窗口背景被設置成 splash_drawable ,通過 setContentView() 設置的佈局都會在 這個背景上繪製,所以我們需要在 setContentView() 把主題設置爲默認的:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(R.style.AppTheme)
setContentView(R.layout.activity_splash)
}
}
設置啓動頁
上面的方法適合簡單的靜態的啓動頁,但是也有許多 app 會加上倒計時或者廣告,那麼只改啓動背景就不能實現了。這是個需要一個單獨的 activity 來實現:
class SplashActivity : AppCompatActivity() {
/**
* CountDownTimer 實現倒計時
*/
private val countDownTimer = object : CountDownTimer(3000, 1000) {
override fun onFinish() {
Intent(this@SplashActivity, MainActivity::class.java).also {
startActivity(it)
}
}
override fun onTick(millisUntilFinished: Long) {
(millisUntilFinished / 1000).toString().let {
tvCountDown.text = it
}
}
};
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(R.style.AppTheme)
setContentView(R.layout.activity_splash)
countDownTimer.start()
}
}
這是一個3秒倒計時的啓動頁,3秒後跳轉主頁。當然別忘記在頁面 destroy 的時候取消倒計時防止內存泄漏。