Android 開發 | 歡迎畫面 Splash Screen
一、前言 歡迎畫面會是使用者打開 App 時,第一個看到的畫面,畫面顯示的時間長度,會根據 App 啟動的速度而有所不同。 在 Android 11 以前,歡迎畫面通常都是白色,但在 Android 12 以後,系統會使用 App Icon 與 App theme 中設定的 windowBackground 製作 App 的歡迎畫面。 如果我們要客製化 App 的歡迎畫面,該怎麼做呢? 二、常見的幾個老方法 在看官方推薦的做法前,先來看一下幾個常見的老方法。 以下討論,讓我們先假設 App 的進入點為專案預設的 MainActivity。 2-1 在 MainActivity 前新增一個 SplashScreenActivity 新增一個 SplashScreenActivity。 在 SplashScreenActivity 的 UI 中繪製歡迎畫面。 使用 Thread.sleep() 設定等待秒數。 執行完後跳轉到 MainActivity。 簡單、直覺的一個方法。 設計師要一個歡迎畫面,我就刻一個出來。 搭配 Thread.sleep(),要顯示幾秒就顯示幾秒。 不過,在 SplashScreenActivity 顯示前,使用者還是會看到系統預設的歡迎畫面。 實際進入 App 的使用體驗可能會跟設計師預期的不同,而且有可能等待時間比預期的還要久。 2-2 SplashScreenActivity 搭配 windowBackground 新增一個 SplashScreenActivity。 在 /drawable 中新增一個 layer-list 的 splash_backgroun.xml 1 2 3 4 5 6 7 <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/white" /> <item android:drawable="@drawable/ic_icon_vector" android:gravity="center"/> </layer-list> 在 themes.xml 中新增 SplashScreenTheme。 1 2 3 4 <!-- Splash Screen theme. --> <style name="SplashScreenTheme" parent="Theme.AppCompat.NoActionBar"> <item name="android:windowBackground">@drawable/splash_background</item> </style> 設定 SplashScreenActivity 的 Theme。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="yourpackage"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".SplashScreenActivity" android:theme="@style/SplashScreenTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity" /> </application> </manifest> SplashScreenActivity 執行完後跳轉到 MainActivity。 1 2 3 4 5 6 7 8 public class SplashScreenActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startActivity(new Intent(SplashScreenActivity.this, MainActivity.class)); finish(); } 跟前一個方法很類似,不過因為是使用 windowBackground 的設定,使用者不會看到系統的歡迎畫面。 ...