文章目錄
- 定義主題theme
- theme配置相關屬性
- 支持延伸到劉海屏&沉浸式佈局
- drawable設計爲layer-list方式
AndroidManifest定義theme
<activity
android:name=".modules.welcome.SplashActivity"
android:screenOrientation="portrait"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
drawable文件夾的style.xml
<!-- 防止歡迎頁白屏或者黑屏,設置圖片 -->
<style name="SplashTheme" parent="AppTheme">
<item name="android:background">@drawable/drawable_splash</item>
<item name="windowNoTitle">true</item>
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowFullscreen">true</item>
</style>
drawable-v28下的style.xml
用於兼容Android 9的劉海屏
<!-- 防止歡迎頁白屏或者黑屏,設置圖片 -->
<style name="SplashTheme" parent="AppTheme">
<item name="android:background">@drawable/drawable_splash</item>
<item name="windowNoTitle">true</item>
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowFullscreen">true</item>
<!--不讓windowBackground延申到navigation bar區域-->
<item name="android:windowDrawsSystemBarBackgrounds">false</item>
<item name="android:windowTranslucentNavigation">true</item>
<!--適配Android P劉海屏-->
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
</style>
drawable_splash.xml
定義冷啓動的背景,爲了適配,採用layer-list
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<color android:color="@color/common_white_color" />
</item>
<item android:bottom="175dp">
<bitmap
android:gravity="center_vertical|left"
android:src="@drawable/pic_splash_icon" />
</item>
<item android:bottom="50dp">
<bitmap
android:gravity="center_horizontal|bottom"
android:src="@drawable/pic_splash_logo" />
</item>
</layer-list>
指定劉海屏顯示模式
Google 爲劉海屏顯示方式提供了三種顯示模式:
// 默認情況,全屏頁面不可用劉海區域,非全屏頁面可以進行使用
public static final int LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT = 0;
// 允許頁面延伸到劉海區域
public static final int LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES = 1;
// 不允許使用劉海區域
public static final int LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER = 2;
style.xml 中配置theme屬性
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
代碼中指定
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
getWindow().setAttributes(lp);
}