结合applyDayNight()与自定义主题叠加?



androidx中,您可以轻松地在日间/夜间模式之间切换。例如:

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

切换主题时:

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

现在,假设我想为白天或夜晚的主题添加一个小定制:

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

我如何做到这一点?

也许你需要一个文件夹——[values-night]

在theme.xml(或style.xml)中,您可以像这样设置当天的主题:

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

在theme-night.xml(或style-night.xml)中:

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

在样式中,你应该初始化这些:

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

关键在ThemeOverlay, ThemeOverlay.MyTheme. daycustom或ThemeOverlay.MyTheme的父元素。NightCustom,是",因为系统会自动识别它是ThemeOverlay,并且只需更改您设置的样式,如colorPrimary,colorPrimaryDark…

最新更新