Member-only story

Making an AlertDialog in Android

Suragch
4 min readJan 3, 2019

--

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

import android.support.v7.app.AlertDialog;public class MainActivity extends AppCompatActivity {    public void showAlertDialogButtonClicked(View view) {        // setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My title");
builder.setMessage("This is my message.");
// add a button
builder.setPositiveButton("OK", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
}
}

Two buttons

public class MainActivity extends AppCompatActivity {    public void

--

--

Suragch
Suragch

Written by Suragch

Flutter and Dart developer. Twitter: @suragch1, Email: suragch@suragch.dev

Responses (3)