MaterialComponents theme alert dialog buttons

If you are using the Material Components library the best way to have an AlertDialog is to use the MaterialAlertDialogBuilder.

new MaterialAlertDialogBuilder(context)
            .setTitle("Dialog")
            .setMessage("Lorem ipsum dolor ....")
            .setPositiveButton("Ok", /* listener = */ null)
            .setNegativeButton("Cancel", /* listener = */ null)
            .show();

It is the default result:

enter image description here

If you want also to apply a different style or color to the buttons you can check this answer.


I figured out what was causing this problem. I need to use different AlertDialog class:

androidx.appcompat.app.AlertDialog

When I switched to this everything started working as expected. Here's where I found the solution:

https://github.com/material-components/material-components-android/issues/162


When using com.google.android.material:material:1.0.0 and androidx.appcompat.app.AlertDialog you can customize each button in the buttonBar by using Widget.MaterialComponents.Button.TextButton as parent.

val builder: AlertDialog.Builder = AlertDialog.Builder(ContextThemeWrapper(context, R.style.AlertDialogTheme))

Use the default layout or add a custom by builder.setView(R.layout.my_dialog)

In your styles:

<style name="AlertDialogTheme" parent="Theme.MaterialComponents.Light.Dialog.Alert">
    <item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
    <item name="buttonBarNegativeButtonStyle">@style/Alert.Button.Neutral</item>
    <item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>
</style>

<style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="backgroundTint">@color/transparent</item>
    <item name="rippleColor">@color/colorAccent</item>
    <item name="android:textColor">@color/colorPrimary</item>
    <item name="android:textSize">14sp</item>
    <item name="android:textAllCaps">false</item>
</style>

<style name="Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
    <item name="backgroundTint">@color/transparent</item>
    <item name="rippleColor">@color/colorAccent</item>
    <item name="android:textColor">@color/gray_dark</item>
    <item name="android:textSize">14sp</item>
</style>

Screenshot