Thursday, July 8, 2010

Displaying a simple message box in Android

There are 2 options to display a pop-up in Android (both are not blocking):
Toast - display a short balloon pop-up that will disappear after few seconds
AlertDialog - display a pop-up window with buttons.

Toast:

Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show();


AlertDialog:

AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("Hello World");
ad.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();


Note: it's better to use "this.getString(R.string.ok)" and get the string from a resource file.

7 comments:

DaNieLo said...

thank you so much! Just what I was looking for.

evry1falls said...

in your example :
what is the button name in XML String file (string.xml)

Sagi said...

@evry1falls - For simplicity the example does not use strings.xml.

You can use resource file for the button name this way:
ad.setButton(getString(R.string.button_name), ......

Vlad Spreys said...

Thank you very much! Very helpful snippet.

Erhan Cetin said...

Take a look here , this is my solution for it with source code:


http://www.erhancetin.com.tr/2013/10/how-to-display-alert-dialog-in-android.html

Steve said...

deprecated solution. use a dialogbuilder instead


AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);

dlgAlert.setMessage("This is an alert with no consequence");
dlgAlert.setTitle("App Title");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();

dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});

Leslie Lim said...

This is really interesting and knowledgeable. Thanks for sharing. I really appreciate it a lot. Please do more blogs in the future. Thank you and God bless to the blogger!

Rica
www.imarksweb.org