Search code examples
androidandroid-alertdialogandroid-themeandroid-stylesmaterial-components-android

how to change the button text color on AlertDialog globally using style?


on android O when i do this :

  <style name="MyTheme" parent="@android:style/Theme.Material.Light.NoActionBar"> 

    <item name="android:textColor">#ff0000</item>

  </style>

The text button color of my alertdialog change, but this not work under lollipop. Worse on lollipop it's change the color of the title of the alertdialog instead.

How from kitkat to android O I can globally change the font color of the button of all my alertdialog ?


Solution

  • With the MaterialComponents theme and the MaterialAlertDialogBuilder you can define globally the style using the materialAlertDialogTheme attribute in your app theme.

    Something like:

    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
       <item name="materialAlertDialogTheme">@style/My_MaterialAlertDialog</item>
    </style>
    

    Then you can define a custom style:

      <style name="My_MaterialAlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
        <!-- Style for positive button -->
        <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
        <!-- Style for negative button -->
        <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
        <!-- Style for neutral button -->
        <item name="buttonBarNeutralButtonStyle">@style/NeutralButtonStyle</item>
      </style>
    

    with the button style defined by:

      <style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button">
        <item name="android:textColor">#FFFFFF</item>
        <item name="backgroundTint">@color/primaryDarkColor</item>
      </style>
    
      <style name="NegativeButtonStyle" parent="@style/Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:textColor">@color/primaryDarkColor</item>
      </style>
    
      <style name="NueutralButtonStyle" parent="@style/Widget.MaterialComponents.Button.TextButton.Dialog">
        ....
      </style>
    

    With the version 1.1.0 of the library you can also simply override the default color using the materialThemeOverlay in the custom style:

      <style name="My_MaterialAlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
          <item name="materialThemeOverlay">@style/DialogButtonOverlay</item>
      </style>
    
      <style name="DialogButtonOverlay">
        <item name="colorPrimary">@color/...</item>
      </style>