Search code examples
androidstylesmaterial-design

Android Theming/Colors: Accent color completely invisible when setting a primary color


A bit of overview on my app: I'm using the Google Material Components library, so my app theme has the parent Theme.MaterialComponents.DayNight.

The issue I'm having is with the colors of my theme. The main place that this is a problem is in a DialogFragment that I've defined. If I declare my theme like this, with explicit primary, primaryDark, and accent colors set:

<style name="DarkTheme" parent="Theme.MaterialComponents.DayNight">
    <item name="colorPrimary">@color/colorDarkPrimary</item>
    <item name="colorPrimaryDark">@color/colorDarkPrimaryDark</item>
    <item name="colorAccent">@color/colorDarkAccent</item>
</style>

then the buttons of my DialogFragment are completely invisible (they should be colorAccent): enter image description here

If I comment all of the color declarations out of the theme, then the buttons do appear: enter image description here

The problem is of course I want to be able to define my own colors. I've tried just defining a colorPrimary and not defining colorPrimaryDark and colorAccent, but this leads to the same problem of the accent text being completely invisible for some reason.


Solution

  • I'm leaving this up so others can find it, but the answer as always lies in the documentation.

    Inheriting any Theme.MaterialComponents changes the names that you have to give colors. Instead of colorAccent as it is with default Android themes, you have to use colorSecondary.

    See: https://github.com/material-components/material-components-android/blob/master/docs/theming/Color.md

    That's half the problem. The other half is that, when using MaterialComponents, it's best to use the MaterialAlertDialogBuilder. So I switched my dialog builder to be defined like this:

    val builder = MaterialAlertDialogBuilder(it, R.style.AlertDialogTheme)
    

    The final step is the R.style.AlertDialogTheme declaration. In styles.xml, I defined that theme to style alert dialogs, and it looks like this:

    <style name="AlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
        <item name="buttonBarPositiveButtonStyle">@style/AlertButton</item>
        <item name="buttonBarNegativeButtonStyle">@style/AlertButton</item>
        <item name="buttonBarNeutralButtonStyle">@style/AlertButton</item>
    </style>
    

    All that @style/AlertButton does is set the text color to the color we are after:

    <style name="AlertButton" parent="Widget.MaterialComponents.Button.TextButton">
        <item name="android:textColor">@color/colorDarkAccent</item>
    </style>
    

    And finally, the dialog buttons use the color you want.