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), ......

Unknown said...

Thank you very much! Very helpful snippet.

Erhan Çetin 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 Burkert 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
}
});

Anonymous said...

How Can A BlogSpot Site Be This Greater WOW