Login Or Sign up

Combine applyDayNight() with custom theme overlay?

276 Views Asked by At

In androidx you can easily toggle between day/night mode. E.g.:

<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
   <!-- attributes -->
</style>

And when toggling theme:

AppCompatDelegate.setDefaultNightMode(nightMode);
getDelegate().applyDayNight();

Now, let's say I want to add a minor customization to either the day or the night theme:

<style name="LimeTheme" parent="AppTheme">
    <item name="colorPrimary">@color/lime1</item>
    <item name="colorPrimaryDark">@color/lime2</item>
    <item name="colorControlHighlight">@color/lime3</item>
</style>

How do I accomplish that?

1

There are 1 best solutions below

5
pnkj On

May be you need a folder —— [values-night].

In your theme.xml(or style.xml), you can set the day theme like :

<style name="Theme.MyTheme"  parent="Theme.MaterialComponents.DayNight.NoActionBar" >
    <item name="minor customization">@style/ThemeOverlay.MyTheme.DayCustom</item>
</style>

In your theme-night.xml(or style-night.xml):

<style name="Theme.MyTheme"  parent="Theme.MaterialComponents.DayNight.NoActionBar" >
    <item name="minor customization">@style/ThemeOverlay.MyTheme.NightCustom</item>
</style>

And in style,you shoule init these:

<style name="ThemeOverlay.MyTheme.NightCustom" parent="">
    <item name="colorPrimary">@color/nightLime1</item>
    <item name="colorPrimaryDark">@color/nightLime2</item>
    <item name="colorControlHighlight">@color/nightLime3</item>
</style>

<style name="ThemeOverlay.MyTheme.DayCustom" parent="">
    <item name="colorPrimary">@color/dayLime1</item>
    <item name="colorPrimaryDark">@color/dayLime2</item>
    <item name="colorControlHighlight">@color/dayLime3</item>
</style>

The key is in ThemeOverlay, the parent of ThemeOverlay.MyTheme.DayCustom or ThemeOverlay.MyTheme.NightCustom,is "",because the system will automatic recognition it is ThemeOverlay, and just change the style you set,like colorPrimary,colorPrimaryDark...