首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

App 啟動畫面閃爍?Theme 設定無 ActionBar 或統一背景色

     編輯:程式設計綜合問答

現象

App 啟動時,使用 ImageView 全螢幕顯示啟動圖,但之前會閃現一幀預設主題背景 (白/黑/ActionBar)。

原因

Activity 啟動流程:
1. 系統依 theme 繪製預設視窗背景 (含 ActionBar)。
2. onCreate → setContentView 載入佈局。
3. 兩者間有明顯時間差,造成閃爍。

解決方案

方案一:啟動 Theme 設為無 ActionBar 且背景即啟動圖 (推薦)

<!-- styles.xml -->
<style name="AppTheme.Launcher">
    <item name="android:windowBackground">@drawable/launch_bg</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
</style>
<!-- drawable/launch_bg.xml (layer-list) -->
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@color/white"/>
    <item>
        <bitmap android:gravity="center" android:src="@mipmap/launch_image"/>
    </item>
</layer-list>
<!-- AndroidManifest.xml -->
<activity android:name=".MainActivity"
    android:theme="@style/AppTheme.Launcher"> ... </activity>

MainActivity onCreate 先 setTheme(R.style.AppTheme) 再 setContentView 切換到正式主題。

方案二:SplashScreen API (Android 12+)

// MainActivity.onCreate 最前
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    getSplashScreen().setOnExitAnimationListener(splashScreenView -> {
        splashScreenView.remove();
    });
}

配合 themes.xml 設定 windowSplashScreenBackground、windowSplashScreenAnimatedIcon。

效果對比

方案閃爍相容性維護成本
windowBackground + Launcher Theme無API 14+低
SplashScreen API無API 31+ (核心庫回溯至 API 21)低
Thread.sleep + 全屏 ImageView有全版本高 (需維護 SplashActivity)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved