[Android] Display Progress Bar After A Dialog In Android

In a previous post, I showed how to add listeners to buttons so that you can modify its text when its in focus or it has been clicked. The listener can be easily modified to show an alert dialog. You can use a ready-built dialog by using the AlertDialog.Builder class. The simplest way creating a dialog:

AlertDialog.Builder builder = new AlertDialog.Builder(AndroidDialog.this);
builder.setMessage("Test alert dialog");
AlertDialog dialog = builder.create();

If you compile and execute this code, you will notice that this will display a dialog with the message “Test alert dialog”, but no buttons! This is pretty useless! To add a button, we must first create another listener for the dialog’s button. This time the listener implements android.content.DialogInterface.OnClickListener. For this example, I have the listener create a progress dialog. It should be easy for you to figure out how to modify the listener to something else.

private class ShowProgress implements DialogInterface.OnClickListener
    public void onClick(DialogInterface arg0, int arg1) {
        ProgressDialog dialog = ProgressDialog.show(
                                    "Progress dialog test");

Now, we have to modify the way we create the dialog to tell the dialog builder to use this listener for the OK action by using its setPositiveButton method.

AlertDialog.Builder builder = new AlertDialog.Builder(AndroidDialog.this);
DialogInterface.OnClickListener listener = new ShowProgress();
builder.setMessage("Test alert dialog");
builder.setPositiveButton("Progress", listener);
AlertDialog dialog = builder.create();

This has added a button labelled “Progress” to the first dialog. Clicking on this button will trigger the listener that creates the progress dialog and displays it.


3 Responses to [Android] Display Progress Bar After A Dialog In Android

  1. sheff says:

    Hi. It is very useful post. Thank you.

  2. ohnoezitasploded says:

    I’m lost on the line:
    builder.setPositiveButton(“Progress”, listener);

    Where is listener in the code? I’m new at this so maybe if there was a complete set of code I could download I could understand this.


    • kahgoh says:


      The ShowProgress (this is already listed above!) class is actually the listener. You can tell because it implements the OnClickListener interface.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: