【问题标题】:Combine applyDayNight() with custom theme overlay?将 applyDayNight() 与自定义主题覆盖相结合?
【发布时间】:2021-02-21 11:52:33
【问题描述】:

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>

我该如何做到这一点?

【问题讨论】:

    标签: android androidx theme-daynight


    【解决方案1】:

    可能你需要一个文件夹——[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...

    【讨论】:

    • 您如何让getDelegate().applyDayNight() 为这个主题叠加层提供帐号?
    • 系统会自动计算。因为你在theme-night.xml(或style-night.xml)中设置了&lt;item name="minor customization"&gt;@style/ThemeOverlay.MyTheme.NightCustom&lt;/item&gt;
    • 我需要日/夜主题加上一个可选覆盖。例如。光,暗,超暗。给定SharedPreferences 中的布尔设置,如何使其成为可选?
    • 只在你的相关Activity中使用setTheme(**)
    • 好的,所以你建议人们应该选择退出自动日/夜内容并简单地应用完整样式?当然,这会起作用,但它会更慢。通过applyDayNight() 现有的日/夜主题非常快。我正在寻找一种将一些自定义样式注入到 Google 正在使用的“快速方法”中的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2015-02-15
    • 2016-05-27
    相关资源
    最近更新 更多