I don't make alerts very often but every time I do it takes me a while to read through the documentation and figure out how to do it. Since I have had to do this a few times now, I am going to write an answer below that I can come back to in the future. Specifically I want to compare the basic code for
- One button (OK)
- Two buttons (OK and Cancel)
- Three buttons (Positive, Negative, Other)
It would be nice to have the basic code for these three common alert types in one spot for easy reference and modification in the future. This question asks how to do it for one button.
I am adding my answer below.
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
wasnull
in the above examples. You can replacenull
with a listener to do something when the user taps a button. For example: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.
Notes
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
I omitted the
onCreate
method in the examples above for brevity. There was nothing special there.See also