1

I'm trying to adopt best practice for managing light and dark mode in my app, based on guidance here and here.

Based on this, I am using a theme inherited from DayNight:

In Manifest:

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

In 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>

This has the desired effect of opening up an Activity in a light or dark theme, based on the device's system setting.

But I want to give the user the option of overriding the mode, e.g. to be always dark (even if the system is in light mode).

But when the system is in light mode, I'm finding that that my Activity initially opens up with a light theme (flash of white), before I get the chance to switch over to the dark theme. I'm switching as soon as I possibly can in the Activity lifecycle:

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

But even then, I'm getting an annoying "flash of light" before the Activity switches over to dark.

How do I avoid the flash of light?

4

1 回答 1

2

我从这个项目中学到了一些关于如何正确做事的教学。

他们在上面的示例应用程序中所做的是在 Manifest 中指定一个主题,但巧妙的是,该主题在主题的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" />

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

<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>

通过在 Manifest 中指定DayNight主题,您可以在 Activity 开始时立即获得正确的主题,而不会乱七八糟。

于 2020-02-19T08:48:52.453 回答