Posted by: kahgoh on: 1 July, 2008
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();
dialog.show();
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
{
@Override
public void onClick(DialogInterface arg0, int arg1) {
ProgressDialog dialog = ProgressDialog.show(
AndroidDialog.this,
"Experimental",
"Progress dialog test");
dialog.setProgress(500);
}
}
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();
dialog.show();
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.
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.
Thanks!
1 | sheff
21 October, 2009 at 1:41 am
Hi. It is very useful post. Thank you.