在活动生命周期中何时覆盖黑暗模式?

时间:2020-02-13 21:18:32

标签: android android-darkmode

我正在尝试根据指导herehere采用最佳实践来管理应用中的明暗模式。

基于此,我正在使用从DayNight继承的主题:

在清单中

<application
    android:theme="@style/Theme.MyApp"
</application>

在themes.xml中:

<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorButtonNormal">@color/colorButtonNormal</item>
</style>

根据设备的系统设置,以浅色或深色主题打开“活动”具有理想的效果。

但是我想给用户覆盖模式的选项,例如始终保持黑暗(即使系统处于亮模式)。

但是,当系统处于浅色模式时,我发现我的活动最初以浅色主题(白色闪烁)打开,然后才有机会切换到深色主题。我将在“活动”生命周期中尽快进行切换:

@Override
protected void onCreate(Bundle savedInstanceState) {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    super.onCreate(savedInstanceState);
    // ...

但是即使那样,在“活动”切换为黑暗之前,我仍然会遇到恼人的“闪光”。

如何避免闪光?

1 个答案:

答案 0 :(得分:1)

我从this project那里学到了一些有关如何正确做事的教导。

他们在上面的示例应用程序中所做的工作是在清单中指定一个主题,但是巧妙地将该主题替换为主题的night变体:

src/main/res/values/themes.xml中:

<style name="Base.MaterialGallery" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    ... some base styling ...
</style>

<style name="Theme.MaterialGallery" parent="Base.MaterialGallery">
    ... styling specific to LIGHT theme ...
</style>

<style name="Theme.MaterialGallery.DayNight" parent="Theme.MaterialGallery" />

上面的最后一个是清单中的设置:

<application
    android:name=".MaterialGalleryApplication"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher"
    android:supportsRtl="true"
    android:theme="@style/Theme.MaterialGallery.DayNight"
    tools:ignore="GoogleAppIndexingWarning">

DayNight中,src/main/res/values-night/themes.xml主题在黑暗模式下被覆盖:

<style name="Theme.MaterialGallery.DayNight" parent="Theme.MaterialGallery">
    ... styling specific to DARK theme (since we're in the NIGHT values-night/themes.xml ...
</style>

通过在清单中指定DayNight主题,您可以在活动开始时立即获得正确的主题,而不会造成混乱。