Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add message box with 'OK' button?

I want to display a message box with an OK button. I used the following code but it results in a compile error with argument:

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

How should I go about displaying a message box in Android?

like image 217
Rajkumar Reddy Avatar asked Jun 07 '11 11:06

Rajkumar Reddy


People also ask

What is message box control?

a title that can represent the source of the message. an icon for each message type to determine how critical a message box is. a brief text message. some command buttons that can represent a user decision.


2 Answers

I think there may be problem that you haven't added click listener for ok positive button.

dlgAlert.setPositiveButton("Ok",     new DialogInterface.OnClickListener() {         public void onClick(DialogInterface dialog, int which) {           //dismiss the dialog           }     }); 
like image 110
Paresh Mayani Avatar answered Oct 12 '22 23:10

Paresh Mayani


Since in your situation you only want to notify the user with a short and simple message, a Toast would make for a better user experience.

Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_LONG).show(); 

Update: A Snackbar is recommended now instead of a Toast for Material Design apps.

If you have a more lengthy message that you want to give the reader time to read and understand, then you should use a DialogFragment. (The documentation currently recommends wrapping your AlertDialog in a fragment rather than calling it directly.)

Make a class that extends DialogFragment:

public class MyDialogFragment extends DialogFragment {     @Override     public Dialog onCreateDialog(Bundle savedInstanceState) {          // Use the Builder class for convenient dialog construction         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());         builder.setTitle("App Title");         builder.setMessage("This is an alert with no consequence");         builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {             public void onClick(DialogInterface dialog, int id) {                 // You don't have to do anything here if you just                  // want it dismissed when clicked             }         });          // Create the AlertDialog object and return it         return builder.create();     } } 

Then call it when you need it in your activity:

DialogFragment dialog = new MyDialogFragment(); dialog.show(getSupportFragmentManager(), "MyDialogFragmentTag"); 

See also

  • Android Alert Dialog with one, two, and three buttons

enter image description here

like image 20
Suragch Avatar answered Oct 12 '22 22:10

Suragch