Search code examples
androidmaterial-designandroid-alertdialogmaterial-components-androidmaterial-components

Android MaterialAlertDialog without extending Theme.MaterialComponent


I'm extending from 'Theme.AppCompat.Light.NoActionBar' and I don't want to switch my AppTheme to MaterialDesign

MaterialAlertDialogBuilder(context, R.style.MaterialDialog)
            .setCancelable(false)
            .setMessage(message)
            .setPositiveButton("OK") { dialog, _ -> dialog.dismiss() }
            .show()
<style name="MaterialDialog" parent="Theme.MaterialComponents.Light.NoActionBar">
        <item name="colorSurface">#ffffff</item>
    </style>

Expcted

What I expected:

Result:

What I got:


Solution

  • If you can't move to a Material Components Theme you should use a Bridge theme. Something like:

    <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar.Bridge">
        <item name="colorSurface">#ffffff</item>
        ...
    </style>
    

    Then in your code just use:

    MaterialAlertDialogBuilder(context)
       .setCancelable(false)
       ...
    

    If you want to override the colors only for the dialog just use:

    MaterialAlertDialogBuilder(context,R.style.MaterialDialog)
       .setCancelable(false)
       ...
    

    with:

      <style name="MaterialDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
        <item name="materialThemeOverlay">@style/AlertDialogOverlay</item>
      </style>  
    
    
      <style name="AlertDialogOverlay">
        <item name="colorOnSurface">@color/....</item>
        <item name="colorSurface">#ffffff</item>
        <item name="colorPrimary">@color/.....</item>
        ....
      </style>