Home » Android » Android Applications » Alert Dialog with Buttons in Material components in Android

Alert Dialog with Buttons in Material components in Android

In our previous post, “Show alert dialog with options on click on Button in Android” we have shown how you can write alert dialog with options on click of a button and the alert dialogs were shown using default AppCompat theme.

In this post we will show how to write alert dialogs using material theme. This alert dialogs are much better than AppCompat theme and preferred to use.

import com.google.android.material.dialog.MaterialAlertDialogBuilder

new MaterialAlertDialogBuilder(MemberViewProfile.this, R.style.AlertDialogTheme)
    .setTitle("Contacts are secured")
    .setMessamport utills.AppConstants;
ge("To view the contact number, birth date and other personal details, you need to upgrade membership.")
    .setPositiveButton("Upgrade Membership", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Intent newIntent = new Intent(MemberProfile.this, UpgradeMembershipActivity.class);
            newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            MemberProfile.this.startActivity(newIntent);

        }
    })
    .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    })
    .show();

Now, update the styles.xml to use the AlertDialog theme,

$ vim app/src/main/res/values/styles.xml
<style name="AlertDialogTheme">
   <item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
   <item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>
</style>
<style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
   <item name="backgroundTint">@color/colorPrimaryDark</item>
   <item name="rippleColor">@color/colorAccent</item>
   <item name="android:textColor">@android:color/white</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">@android:color/transparent</item>
   <item name="rippleColor">@color/colorAccent</item>
   <item name="android:textColor">@android:color/darker_gray</item>
   <item name="android:textSize">14sp</item>
</style>

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment