问题描述
在 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>
key在ThemeOverlay中,ThemeOverlay.MyTheme.DayCustom或ThemeOverlay.MyTheme.NightCustom的父级为"",因为系统会自动识别它是ThemeOverlay,只需改变样式你设置,比如 colorPrimary,colorPrimaryDark...