Making an AlertDialog in Android

This is an expansion of an answer I wrote on Stack Overflow.

AlertDialogs are useful for displaying a message to a user and optionally giving them a chance to respond to it. This is the equivalent of an iOS UIAlertController (or a Flutter AlertDialog). The examples below show a basic setup for one, two, and three buttons.

One button

Two buttons

Three buttons

If the button text it too long to all fit horizontally, then it will automatically get laid out in a vertical column of three buttons.

Handling Button Clicks

The OnClickListener was null in the above examples. You can replace null with a listener to do something when the user taps a button. For example:

Changing the button color

By default the button colors are the same color as the colorAccent in the base application theme, which is set in your styles.xml file.

You can change the color as simply as changing the colorAccent hex value in your colors.xml file.

However, this will change the accent color all across your app. If you only want to change it for the dialog, you can make a custom theme. Add the following to your styles.xml file:

This overrides colorAccent. Next define the dialogButtonText color in colors.xml:

Now whenever you create a dialog you can just pass in the custom theme. Replace the AlertDialog.Builder line in the examples above with the following code:

If you want more control over the color of individual buttons, see the answers to this Stack Overflow question.

Notes

  • Use string resources rather than hard coded strings.
  • You can wrap everything in a class that extends DialogFragment for easy reuse of a dialog. (See this for help.)
  • These examples used the support library to support versions prior to API 11. So the import should be import android.support.v7.app.AlertDialog;
  • I omitted the onCreate method in the examples above for brevity. There was nothing special there.

Going On

There are many more varieties of dialogs that you can make. See the documentation for help with this.

Since only three buttons are supported in an AlertDialog, here is an example of a dialog with a list.

See this answer for similar examples of a radio button list and a checkbox list.

See also

A Flutter and Dart developer. Follow me on Twitter @suragch1 to get updates of new articles.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store