Sunday, March 6, 2011

Showing Dialog in Android Application

First, different from other platforms, showing dialog in Android will not block the current execution. So that the code behind Dialog.show() will be executed immediately without waiting the dialog gets closed. As a result, anything that needs to be called after closing the dialog should be put into dialog's button handling method.

Second, there is not a single method that can be called to show a dialog. The simplest code to show a dialog box is as follows

Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("my title");
alertDialog.setMessage("my message.");
alertDialog.show();

Third, if you do not want user to cancel the dialog by selecting the back key, then call the following method before alertDialog.show();
alertDialog.setCancelable(false);

Finally, if you want user to select a yes/no option by clicking a button in the dialog box, two other methods should be called to set these button's text and callback methods. A full functioning dialog is showing below:

AlertDialog.Builder ad = new AlertDialog.Builder(myActivity.this);
ad.setTitle("my title");
ad.setMessage("my message");
ad.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
// do yes operation
}
});

ad.setNegativeButton("No", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
// do no operation
}
});

ad.setCancelable(true);
ad.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// do cancel operation
}
});

ad.show();


Note if you show two dialogs (that is, calling Dialog.show()) within a single method, then the second dialog will show on the top of the first one. Only after the second dialog gets dismissed, then the first one will become the active dialog.

Jonathan

No comments:

Post a Comment