Android: Dialogs

Emrullah Lüleci
Android Bits
Published in
2 min readMar 16, 2017
Credit: material.io

Dialogs inform users about a specific task and may contain critical information, require decisions, or involve multiple tasks.

Dialogs contain text and UI controls. They retain focus until dismissed or a required action has been taken. Use dialogs sparingly because they are interruptive.

(Material Design Guidelines)

Create and show dialog in JAVA:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.components_dialog_alert_title);
builder.setMessage(R.string.components_dialog_alert_message);
builder.setPositiveButton(R.string.components_dialog_alert_positive,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(DialogActivity.this,
R.string.components_dialog_alert_positive,
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(DialogActivity.this,
android.R.string.no, Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);
builder.show();

If you want you can remove builder variable and chain all builder methods.

The result is:

Most common setter methods of the AlertDialog.Builder are:

  • setTitle : Sets the dialog title.
  • setMessage : Sets the content text.
  • setPossitiveButton : Sets the text and the click listener of the possitive button.
  • setNegativeButton : Sets the text and the click listener of the negative button. Negative button is placed at left if both of the buttons provided.
  • setCancelable : Defines if the dialog can be dismissed by clicking the area around it.
  • setIcon : Sets the icon. The icon is shown at left of the title.
  • setOnDismissListener : Sets the listener which is called when the dialog is dismissed.

Text related setters such as title, message, positive and negative button labels accept both string resource id and string. You can choose either but of course the recommended way would be using resource id.

That’s it. Cheers.

--

--