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.makeText(this, "Hello World", Toast.LENGTH_SHORT).show();


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() {
public void onClick(DialogInterface dialog, int which) {

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


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:

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);

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!