Search code examples
androidandroid-alertdialogandroid-themematerial-components-androidandroid-ktx

Why is my default alert dialog button text white?


I have set up my app as follows:

build.gradle

implementation 'com.google.android.material:material:1.1.0'

styles.xml

    <style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
        <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
        <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    </style>

    <style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:color">@color/colorPrimary</item>
    </style>

    <style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:color">@color/colorPrimary</item>
    </style>

CheckoutFragment.kt

   private fun createConfirmOrderDialog() {
       val builder = AlertDialog.Builder(requireContext(), R.style.AlertDialogTheme)
       builder.setTitle(getString(R.string.confirm_order))
           .setMessage(dialogPrompt)
           .setPositiveButton(R.string.confirm) { dialog, _ ->
               viewModel.placeOrder()
               dialog.dismiss()
           }
           .setNegativeButton(R.string.cancel) { dialog, _ ->
               dialog.dismiss()
           }
       builder.show()
  }

colors.xml

<color name="colorAccent">#F1CB1A</color> // I have this added to the base theme

This setup, however, shows a dialog where the button text is not visible since both text and background is white.

The resulting dialog

How can I fix this?


Solution

  • Use the MaterialAlertDialogBuilder instead of AlertDialog.Builder:

        MaterialAlertDialogBuilder(context)
            .setTitle("Title")
            .setMessage(dialogPrompt)
            .setPositiveButton("OK",listener)
            .show()
    

    The default color of the buttons is based on the colorPrimary color.

    If you want to use a custom color you can use:

        MaterialAlertDialogBuilder(context,R.style.AlertDialogTheme)
    

    with this style

    <style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
        <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
        <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    </style>
    
    <style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:textColor">@color/.....</item>
    </style>
    
    <style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:textColor">@color/....</item>
    </style>