Introduction to AlertDialog

android alertdialog

An AlertDialog is a subclass of a Dialog that can display one, two or three buttons.

AlertDialogs don't require any layout.

AlertDialog was added in Android API level 1.

It resides in the android.app package.

package android.app;

AlertDialog derives from the android.app.Dialog class:

public class AlertDialog 
extends Dialog..{}

AlertDialog implements the DialogInterface interface:

public class AlertDialog 
extends Dialog implements DialogInterface

AlertDialog SubClasses:

Here are some of the classes that directly derive AlertDialog:

No. Class Description
1. DatePickerDialog A simple Dialog that has a DatePicker.
2. ProgressDialog A dialog that shows a progress indicator and an optional text message or view.
3. TimePickerDialog A Dialog that prompts the user for the time of the day using TimePicker.

Use of AlertDialog

  1. To display alert or any information.

Creating AlertDialog

To create an AlertDialog you use the android.app.AlertDialog.Builder class.

  1. First you instantiate the AlertDialog.Builder:
        AlertDialog.Builder myBuilder=new AlertDialog.Builder(this);
  2. Then you create the AlertDialog using the create() method:
        AlertDialog myDialog=myBuilder.create();

Displaying Title and Message

To display only a String you can just use the setMessage() method and to display title you can use the setTitle() method.

        myBuilder.setTitle(R.string.my_title).setMessage(R.string.my_message);

Display Complex View in AlertDialog

To display a more complex view, you can look up a FrameLayout called custom and add your view to it.

FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
 fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));

Showing AlertDialog

To show the AlertDialog you use the show() method:

myDialog.show();

Creating AlertDialog with Buttons

AlertDialogs can have buttons as well as content. So far we've looked at how to display content and title.

However, the AlertDialog.Builder also allows us create buttons:

  1. Positive Button - We can create positive button using the setPositiveButton() method of the AlertDialog.Builder class.
myBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "OK clicked", Toast.LENGTH_SHORT).show();
            }
        });
  1. Negative Button - We can create negative button using the setNegativeButton() method of the AlertDialog.Builder class.
myBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                myDialog.dismiss();
            }
        });
  1. Neutral Button - We can create neutral button using the setNeutralButton() method of the AlertDialog.Builder class.
myBuilder.setNeutralButton("Neutral", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

Simple AlertDialog Android

Android AlertDialog Examples

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.LayoutRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

public class KDialog {

    public static void showImgInDialog(Context context, Bitmap bitmap) {
        ImageView imageView = new ImageView(context);
        imageView.setImageBitmap(bitmap);
        new AlertDialog.Builder(context)
                .setView(imageView)
                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    public static void showMsgDialog(final Context context, final String content) {
        new android.os.Handler(Looper.getMainLooper())
                .post(new Runnable() {
                    @Override
                    public void run() {
                        new AlertDialog.Builder(context)
                                .setMessage(content)
                                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
                    }
                });

    }

    public static void showCustomViewDialog(final Context context, final String title, final View view,
                                            final DialogInterface.OnClickListener positiveListener, final DialogInterface.OnClickListener negativeListener) {
        new Handler(Looper.getMainLooper())
                .post(new Runnable() {
                    @Override
                    public void run() {
                        new AlertDialog.Builder(context)
                                .setTitle(title)
                                .setView(view)
                                .setPositiveButton("确认", positiveListener)
                                .setNegativeButton("取消", negativeListener)
                                .show();
                    }
                });
    }

    public static void showSingleChoiceDialog(final Context context, final String title, CharSequence[] items, final SingleSelectedCallback callback) {
        final int[] selectedIndex = new int[1];
        new AlertDialog.Builder(context)
                .setTitle(title)
                .setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        selectedIndex[0] = which;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            callback.singleSelected(selectedIndex[0]);
                        }
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(false)
                .show();
    }

    public static void showMultiChoicesDialog(final Context context, final String title, CharSequence[] items, final MultiSelectedCallback callback) {
        final int[] selectedItems;
        final boolean[] selected = new boolean[items.length];
        new AlertDialog.Builder(context)
                .setTitle(title)
                .setMultiChoiceItems(items, new boolean[items.length], new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        selected[which] = isChecked;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int size = selected.length;
                        List<Integer> selectedList = new ArrayList<>();
                        if (callback != null) {
                            for (int i = 0; i < size; i++) {
                                if (selected[i]) {
                                    selectedList.add(i);
                                }
                            }
                            if (selectedList != null && selectedList.size() > 0) {
                                callback.multiSelected(selectedList);
                            } else {
                                callback.selectedNothing();
                            }
                        }
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(false)
                .show();
    }

    private static ProgressDialog progressDialog;

    public static void showProgressDialog(final Context context, int progress){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(context);
        }
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.setProgress(progress);
        progressDialog.show();

        if (progress >= 100){
            if (progressDialog != null && progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }

    public interface SingleSelectedCallback {
        void singleSelected(int index);
    }

    public interface MultiSelectedCallback {
        void multiSelected(List<Integer> list);

        void selectedNothing();
    }

}

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post