Android 12+ Splash Screen API如何实现全屏宽度居中横幅启动页?
我想实现一个居中且占满屏幕宽度的横幅式启动页,效果为全屏宽度的横幅居中显示。目前在Android 12以下版本可正常实现,但Android 12及以上版本中,横幅被压缩得仅中间部分可见,还带有圆形阴影。我试过使用android:windowSplashScreenBrandingImage,但该属性仅在API 31+可用,且使用时图标与横幅会同时显示。请问能否在Android 12+中实现这种全屏宽度的横幅启动页?
可以实现,核心思路是绕过Android 12+原生启动页的图标限制,直接使用自定义布局作为启动页,具体步骤如下:
禁用系统默认启动页的图标展示
在values-v31/styles.xml中配置启动页主题,隐藏默认图标与背景:<style name="SplashTheme" parent="Theme.SplashScreen"> <item name="windowSplashScreenBackground">@android:color/transparent</item> <item name="windowSplashScreenAnimatedIcon">@drawable/transparent_empty</item> <item name="postSplashScreenTheme">@style/AppTheme</item> </style>需提前创建一个完全透明的drawable文件(比如
transparent_empty.xml),用来替换系统默认图标。自定义启动页布局
创建全屏的启动页Activity,布局文件中直接放置横幅图片,设置宽度为match_parent以占满屏幕,同时居中显示:<!-- res/layout/activity_splash.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:background="@color/your_splash_bg"> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="fitCenter" android:src="@drawable/your_banner_image"/> </LinearLayout>处理启动页跳转逻辑
在SplashActivity中设置延迟跳转至主Activity,同时兼容Android 12+的启动页过渡:class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) // 可根据需求调整跳转延迟时长 Handler(Looper.getMainLooper()).postDelayed({ startActivity(Intent(this, MainActivity::class.java)) finish() }, 1500) } }配置AndroidManifest文件
将SplashActivity设为启动Activity,并应用上述定义的SplashTheme:<activity android:name=".SplashActivity" android:theme="@style/SplashTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
注:这种方式在Android 12+上会先显示短暂的系统空白过渡(因设置了透明背景),随后立即展示自定义横幅启动页,视觉效果与低版本保持一致。若希望完全消除系统过渡,可结合SplashScreen API的setKeepOnScreenCondition方法优化,基础方案已能满足大多数场景需求。
内容的提问来源于stack exchange,提问作者RagAnt

