Android Alert Dialog Example

android.app.AlertDialog is the class that used to create and manipulate an alert dialog. This article will show you examples about how to implement various Alert Dialog in android application.

android.app.AlertDialog is very powerful, you can use it to create below different types of dialog.

  1. Contains message and confirm buttons alert dialog.
  2. Contains list items and confirm buttons alert dialog.
  3. Contains single choice radio button and confirm buttons alert dialog.
  4. Contains multiple choice checkbox and confirm buttons alert dialog.

1. Steps To Create Android Alert Dialog.

  1. Create an instance of AlertDialog.Builder class.
  2. Call AlertDialog.Builder‘s setTitle(), setIcon(), setMessage() or setItems() method to set related data.
  3. Call AlertDialog.Builder‘s create() method to create the alert dialog.
  4. Call AlertDialog.Builder‘s show() method to show the alert dialog.

2. AlertDialog.Builder Methods.

  1. setTitle() : Set dialog title.
  2. setIcon() : Set dialog icon.
  3. setMessage() : Set the alert dialog display messages.
  4. setPositiveButton() : Set OK button’s text and click event listener.
  5. setNegativeButton() : Set Cancel button’s text and click event listener.
  6. setNeutralButton() : Set Neutral button’s text and click event listener.
  7. setItems() : Set alert dialog’s content with list items.
  8. setSingleChoiceItems() : Set alert dialog’s content with single choice radio button.
  9. setMultiChoiceItems(): Set alert dialog’s content with multiple choice checkbox.
  10. setAdapter() : Set alert dialog’s content with custom defined list items.
  11. setView() : Set alert dialog’s content with custom defined view object.
  12. setCancelable() : Set whether the alert dialog can be canceled or not.
  13. create() : Create an AlertDialog instance.
  14. show() : Show the alert dialog.
  15. AlertDialog.cancel() : Close the alert  dialog. This method belongs to AlertDialog class, AlergDialog.Builder class do not has such method.
READ :   Android RecyclerView Example

3. Android Alert Dialog Examples.

android alert dialog example

3.1 Layout Xml File.

activity_alert_dialog.xml

This file is saved in app / res / layout folder.

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:id="@+id/alertDialogButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Basic Alert Dialog" />

        <Button
            android:id="@+id/alertDialogSimpleListButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Simple List Alert Dialog" />

        <Button
            android:id="@+id/alertDialogSingleChoiceButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Single Choice Alert Dialog" />

        <Button
            android:id="@+id/alertDialogMultipleCheckboxButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Multiple Checkbox Alert Dialog" />

        <TextView
            android:id="@+id/alertDialogTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"/>

    </LinearLayout>

3.2 Activity Java Code.

AlertDialogActivity.java

package com.dev2qa.example;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class AlertDialogActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert_dialog);

        setTitle("dev2qa.com --- Android AlertDialog Example");

        TextView textView = (TextView)findViewById(R.id.alertDialogTextView);

        this.showBasicAlertDialog(textView);

        this.showSimpleListItemsInAlertDialog(textView);

        this.showSingleChoiceRadioInAlertDialog(textView);

        this.showMultipleCheckboxInAlertDialog(textView);

    }

    // Show basic alert dialog.
    private void showBasicAlertDialog(TextView textView)
    {
        final TextView textViewTmp = textView;
        Button alertDialogButton = (Button)findViewById(R.id.alertDialogButton);
        alertDialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(AlertDialogActivity.this);
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("Customized Alert Dialog");
                builder.setMessage("This is a simple alert dialog.");

                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        textViewTmp.setText("You clicked OK button.");
                    }
                });

                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        textViewTmp.setText("You clicked Cancel button.");
                    }
                });

                builder.setNeutralButton("Neutral", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        textViewTmp.setText("You clicked Neutral button.");
                    }
                });

                builder.setCancelable(false);
                builder.show();
            }
        });
    }

    // Show simple list items in alert dialog.
    private void showSimpleListItemsInAlertDialog(TextView textView)
    {
        final TextView textViewTmp = textView;
        Button alertDialogButton = (Button)findViewById(R.id.alertDialogSimpleListButton);
        alertDialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(AlertDialogActivity.this);
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("Customized Alert Dialog");

                final String listItemArr[] = {"Java", "C++", "Python", "Javascript", "Html", "Android"};
                builder.setItems(listItemArr, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int itemIndex) {
                        textViewTmp.setText("You choose item " + listItemArr[itemIndex]);
                    }
                });

                builder.setCancelable(true);

                builder.show();
            }
        });
    }

    // Show single choice radio button in alert dialog.
    private void showSingleChoiceRadioInAlertDialog(TextView textView)
    {
        final TextView textViewTmp = textView;
        Button alertDialogButton = (Button)findViewById(R.id.alertDialogSingleChoiceButton);
        alertDialogButton.setOnClickListener(new View.OnClickListener() {

            private String chooseItem;
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(AlertDialogActivity.this);
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("Customized Alert Dialog");

                final String listItemArr[] = {"Java", "C++", "Python", "Javascript", "Html", "Android"};
                builder.setSingleChoiceItems(listItemArr, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int itemIndex) {
                       chooseItem = listItemArr[itemIndex];
                    }
                });

                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        textViewTmp.setText("You select " + chooseItem);
                    }
                });

                builder.show();
            }
        });
    }

    // Show multiple choice checkbox in alert dialog.
    private void showMultipleCheckboxInAlertDialog(TextView textView)
    {
        final TextView textViewTmp = textView;
        Button alertDialogButton = (Button)findViewById(R.id.alertDialogMultipleCheckboxButton);
        alertDialogButton.setOnClickListener(new View.OnClickListener() {

            // Store user checked checkbox values.
            private Map<String, String> chooseDataMap = new HashMap<String, String>();

            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(AlertDialogActivity.this);
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("Customized Alert Dialog");

                final String listItemArr[] = {"Java", "C++", "Python", "Javascript", "Html", "Android"};
                builder.setMultiChoiceItems(listItemArr, new boolean[]{true, false, false, false, false, false}, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int itemIndex, boolean checked) {
                        String checkboxString = listItemArr[itemIndex];

                        if(checked)
                        {
                            if(chooseDataMap.get(checkboxString)==null) {
                                chooseDataMap.put(checkboxString, checkboxString);
                            }
                        }else
                        {
                            if(chooseDataMap.get(checkboxString)!=null) {
                                chooseDataMap.remove(checkboxString);
                            }
                        }
                    }
                });

                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        textViewTmp.setText("You select " + chooseDataMap.keySet().toString());

                        // Empty the data map.
                        Set<String> keySet = chooseDataMap.keySet();
                        Iterator keySetIt = keySet.iterator();
                        while(keySetIt.hasNext())
                        {
                            // Remove one element.
                            String key = (String)keySetIt.next();
                            chooseDataMap.remove(key);

                            // Recalculate keyset.
                            keySet = chooseDataMap.keySet();
                            keySetIt = keySet.iterator();
                        }
                    }
                });

                builder.show();
            }
        });
    }
}
(Visited 2,749 times, 4 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.