Monday, February 1, 2010

How to add MessageBox in Android?

Simple message box with no buttons
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Packing List");
alertDialog.setMessage("Could not find the file.");
alertDialog.show();

Message box with buttons
AlertDialog deleteAlert = new AlertDialog.Builder(this).create();
deleteAlert.setTitle("Delete List");
deleteAlert.setMessage("Are you sure you want to delete this list?");
deleteAlert.setButton("Yes", new OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {               
//...
}
});
deleteAlert.setButton2("No", new OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {
//...
}
});
deleteAlert.show();

8 comments:

  1. Is there any way to do this without an Activity object? (I want to use it for debugging in classes that don't extend Activity)

    ReplyDelete
  2. You can pass the Activity context to your class to replace "this" in code above.

    ReplyDelete
  3. you can use getContext() method out of activity to replace "this" in code above.

    ReplyDelete
  4. 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

    ReplyDelete
  5. its showing error in setbutton and setbutton2 line
    can tell me the solution for it?

    ReplyDelete
    Replies
    1. Those methods are deprecated. You can use setButton(AlertDialog.BUTTON_POSITIVE, ...) and setButton(AlertDialog.BUTTON_NEGATIVE, ...) instead

      Delete
  6. This comment has been removed by the author.

    ReplyDelete