使用 DayNight 主题时更改启动屏幕中的背景颜色

Change background color in launch screen when using DayNight theme

我正在使用 DayNight 主题和 启动屏幕

启动屏幕是一个白色背景的图层列表。

因此,当天 white 启动屏幕显示后 white activity。但是在晚上,白色 启动屏幕显示 黑暗 activity。

如何根据主题更改启动屏幕的背景颜色。

无法使用自定义颜色属性,因为只有 DayNight 主题。

themes.xml

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:colorControlNormal">@color/colorAccent</item>
</style>

<style name="LaunchTheme" parent="AppTheme">
    <item name="android:windowBackground">@drawable/launch_screen</item>
</style>

launch_screen.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <color android:color="@color/material_white"/>
</item>
<item>
    <bitmap
       android:gravity="center"
       android:src="@drawable/launch_logo"
       android:tileMode="disabled"/>
</item>

除了您的默认启动主题外,请在适当的资源目录中提供其夜间变体。

res/values-night/themes.xml

<style name="LaunchTheme" parent="AppTheme">
    <item name="android:windowBackground">@drawable/launch_screen_night</item>
</style>

res/drawable/launch_screen_night.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <color android:color="@color/material_black"/>
</item>
<item>
    <bitmap
       android:gravity="center"
       android:src="@drawable/launch_logo"
       android:tileMode="disabled"/>
</item>

查了一会儿,找到了答案。

由于启动画面配置是由系统加载的,因此您需要影响系统 UI 模式。

getSystemService<UiModeManager>()?.nightMode = UiModeManager.MODE_NIGHT_YES

但不幸的是,这不是一个干净的解决方案,因为它会影响系统设置。

Changes to night mode take effect globally and will result in a configuration change (and potentially an Activity lifecycle event) being applied to all running apps. Developers interested in an app-local implementation of night mode should consider using AppCompatDelegate.setDefaultNightMode(int) to manage the -night qualifier locally.