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?
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.
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 } });
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With