Search code examples
androidandroid-resourcesandroid-themematerial-components-android

Use Night resources on Light theme


I'm using the Material Component's dark theme style, everything is working fine but now I need to show a particular view with a different theme to obtain more contrast. I've defined my main theme in values/themes.xml like that:

<style name="Base.AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="colorPrimary">@color/color_primary</item>
    <item name="colorPrimaryVariant">@color/color_primary_variant</item>
    <item name="colorOnPrimary">@color/color_on_primary</item>
    ...
</style>

and two different colors resources in values/colors.xml and values-night/colors.xml.

What I would like to do is to find a way to retrieve the light theme colors when the dark theme is used (and vice-versa) or to apply the opposite theme to a single view.

The only solution I found was to simply define two variants (normal and "reversed") for each color in both colors.xml files, but since there are many colors defined I would like to avoid that.


Solution

  • To avoid having to define multiple light/dark values variant for each color, I defined a custom style that refers to the opposite theme variant, e.g. in values/styles.xml I defined:

    <style name="ThemeOverlay.AppTheme.Reverse" parent="ThemeOverlay.MaterialComponents.Dark"/>
    

    and in values-night/styles.xml:

    <style name="ThemeOverlay.AppTheme.Reverse" parent="ThemeOverlay.MaterialComponents.Light"/>
    

    Then in the root of layout where I want to use the "reversed" theme:

    <LinearLayout android:orientation="horizontal"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:theme="@style/ThemeOverlay.AppTheme.Reverse">
    
        ...
    
    </LinearLayout>