Android AlertDialog.Builder example code


public class MyActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Exit!")
            .setMessage("Are you sure you want to exit?")
            .setCancelable(false)
            .setIcon(R.drawable.ic_launcher)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    MyActivity.this.finish();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            })
            .setNeutralButton("Middle", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(MyActivity.this, "Middle button clicked!", Toast.LENGTH_SHORT).show();
                }
            });

        builder.create().show();		// create and show the alert dialog

    }
}
alert with icon and 3 buttons

android alert with icon and 3 buttons

final CharSequence[] items = {"Red", "Green", "Blue"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit!")
    .setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int item) {
            Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
        }
    });

builder.create().show();

alert with single choice item

final CharSequence[] items = {"Red", "Green", "Blue"};
final boolean [] selected = {true, false, true};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick colors")
    .setMultiChoiceItems(items, selected, new DialogInterface.OnMultiChoiceClickListener() {
    public void onClick(DialogInterface dialogInterface, int item, boolean b) {
        Log.d("Myactivity", String.format("%s: %s", items[item], b));
    }
});

builder.create().show();

alert with multi choice items

Utility class with static ShowAlertDialog Method

usually we need three types of alert dialog.

MessageAlert
just to show the information/message. there is only one button, which is essentially named “OK”. For example

messageAlert

Use this alert method when you don’t need to know when user clicked the “OK” button. You want to show the message and you used this method to show it.

ConfirmationAlert
confirm the user that something is gonna happen.

confirmationAlert

Use this alert method when you need to know when user clicked the “OK” button. This is a confirmation type message and you are waiting for the user to hit the “OK” button, as soon as user clicks it, you will start to do something.

DecisionAlert
Decision dialog with two buttons

decisionAlert

User this alert when you need to know an user decision. there will be two button named “YES” or “NO”. If user clicks on “YES” you will do something and if user clicks “NO” you will do something else

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class AlertUtil {

    private static final int MESSAGE_ALERT = 1;
    private static final int CONFIRM_ALERT = 2;
    private static final int DECISION_ALERT = 3;

    public static void messageAlert(Context ctx, String title, String message) {
        showAlertDialog(MESSAGE_ALERT, ctx, title, message, null, "OK");
    }

    public static void confirmationAlert(Context ctx, String title, String message, DialogInterface.OnClickListener callBack) {
        showAlertDialog(CONFIRM_ALERT, ctx, title, message, callBack, "OK");
    }

    public static void decisionAlert(Context ctx, String title, String message, DialogInterface.OnClickListener posCallback, String... buttonNames) {
        showAlertDialog(DECISION_ALERT, ctx, title, message, posCallback, buttonNames);
    }

    public static void showAlertDialog(int alertType, Context ctx, String title, String message, DialogInterface.OnClickListener posCallback, String... buttonNames) {
        if ( title == null ) title = ctx.getResources().getString(R.string.app_name);
        if ( message == null ) message = "default message";

        final AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setTitle(title)
                .setMessage(message)

                // false = pressing back button won't dismiss this alert
                .setCancelable(false)

                // icon on the left of title
                .setIcon(android.R.drawable.ic_dialog_alert);

        switch (alertType) {
            case MESSAGE_ALERT:
                break;

            case CONFIRM_ALERT:
                builder.setPositiveButton(buttonNames[0], posCallback);
                break;

            case DECISION_ALERT:
                break;
        }

        builder.setNegativeButton(buttonNames [buttonNames.length - 1], new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).create().show();
    }
}

Sample Usage

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;

public class MyActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        AlertUtil.messageAlert(this, "title", "message");
        
        AlertUtil.confirmationAlert(this, "title", "message", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // do something important, user confirmed the alert 
            }
        });
        
        AlertUtil.decisionAlert(this, "title", "message", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // do something because user clicked the positive button 
            }
        });
    }
}
About these ads

5 thoughts on “Android AlertDialog.Builder example code

  1. platform is a very generic word ..
    you can develop android in any os: windows/mac/linux
    language: basically java ,.. then, C/C++/python/javascript/lua and may be some others

  2. hi i have a doubt. i am using alertdialog.builder to show image enlarged. after shown, on emulator if i click any where outside the dialog the dialog closes. but this wont happen on device. can you explain why ?

  3. Trackback Submitter is world’s first software which can speed-up website indexing, boost search engine rankings, increase traffic and supercharge overall income with the help of trackback links. Furthermore, it’s the only tool which enables using trackbacks for promoting not only blogs, but also all other types of websites. visit this link – http://bitly.com/PkozGw

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s