Lesson 60. Dialogues. AlertDialog: Title, Message, Icon, Buttons

Lesson 60. Dialogues. AlertDialog: Title, Message, Icon, Buttons

In this lesson:

– create AlertDialog
– customize the title, message, picture and buttons

Let’s get started with AlertDialog. this dialogue is used if you want to report something to the user or ask him / her to select Yes / No / Cancel.

Let’s write the program which at closing will cause dialogue about data storage, similar to dialogue from MS Office programs. If we answer Yes, the data will be saved, if No – then it will not be saved, if Cancel – the program will not close.

Let’s create a project:

Project name: P0601_AlertDialogSimple
Build Target: Android 2.3.3
Application name: AlertDialogSimple
Package name: ru.startandroid.develop.p0601alertdialogsimple
Create Activity: MainActivity

Add to res / values ​​/ strings.xml lines with texts:

    Сохранить данные?

screen main.xml:


code MainActivity.java:

package ru.startandroid.develop.p0601alertdialogsimple;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
  final int DIALOG_EXIT = 1;
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    public void onclick(View v) {
      // вызываем диалог
    protected Dialog onCreateDialog(int id) {
      if (id == DIALOG_EXIT) {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        // заголовок
        // сообщение
        // иконка
        // кнопка положительного ответа
        adb.setPositiveButton(R.string.yes, myClickListener);
        // кнопка отрицательного ответа
        adb.setNegativeButton(R.string.no, myClickListener);
        // кнопка нейтрального ответа
        adb.setNeutralButton(R.string.cancel, myClickListener);
        // создаем диалог
        return adb.create();
      return super.onCreateDialog(id);
    OnClickListener myClickListener = new OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
      switch (which) {
      // положительная кнопка
      case Dialog.BUTTON_POSITIVE:
      // негативная кнопка
      case Dialog.BUTTON_NEGATIVE:
      // нейтральная кнопка  
      case Dialog.BUTTON_NEUTRAL:
  void saveData() {
    Toast.makeText(this, R.string.saved, Toast.LENGTH_SHORT).show();

In the button handler onclick we invite dialogue.

IN onCreateDialog we create a dialogue. This is done using the class AlertDialog.Builder. We indicate the title, message text, icon and buttons. The dialog can have a maximum of three answer buttons: positive, negative and neutral. For each we specify the text and the handler. The create method creates a dialog and we return it.

button handler myClickListener implements the DialogInterface.OnClickListener interface and in our case is common to all buttons. In it, we check which button was pressed:
if positive (BUTTON_POSITIVE), then we save the data and close the application
if negative (BUTTON_NEGATIVE) then close the application without saving
if neutral (BUTTON_NEUTRAL) we do nothing

In our saveData method, we output text that the data appears to be stored. Just to make sure the method is implemented.

We will save everything and launch the application. Click the Exit button:

if we click So,

then the application will close and method saveData will be executed.

if we click Cancel, Then the dialog will close and nothing will happen with the application.
And if we click no, Then the application will close without a call of our method saveData.

It is so easy and short-lived to create a dialogue for user interaction. We used dialogue attributes are optional. For example, you may not specify a title, or make only one button, not three.

It is not necessary to use variables to specify the title, message and button text R.string. There are similar implementations of methods that simply accept text.

And some more tips.

1) That the dialogue was caused not only by the exit button, but also by pressing the button back in the app, add a dialog call to the onBackPressed implementation

public void onBackPressed() {
  // вызываем диалог

2) And if you want to prevent the called dialog from closing after pressing the Back button, then use the setCancelable method:


In the next lesson:

– we use the method of preparing the dialogue

Discuss in the forum [59 replies]

Leave a Comment