Alert Dialog Box in Android

A dialog is a small windows that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is used to take an action before they can proceed. Some example of Alert Dialog Box are:

how to show alert dialog box in android
  • The Dialog class is the base class for dialog, but we should avoid instantiating Dialog directly instead use one of the following sub-classes.

AlertDialog: a dialog that can show a title, up to three buttons, a list of selected items, or a custom layout.

DatePickerDialog or TimePickerDialog: A dialog with a predefined UI that allows user to select a date or time.

  • Creating AlertDialog: create as:

AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this)

it has has three regions:

  1. Title
  2. Content area
  3. Action button
how to show alert dialog box in android?

Three different action button:

  1. positive: we should use this to accept and continue with the action (the “ok” action).
  2. Negative: we should use this to cancel the action.
  3. Neutral: we should use this when the user may not want to proceed with the action but does not necessarily want to cancel.

Dismissing the dialog:

When the user touches any of the action buttons created with an AlertDiaog.Builder the system dismisses the dialog for us otherwise we can manually dismiss the dialog by calling dismiss().

Source Code:

1. Declare the button and textfield inside the main activity class as:


Button _btnlogin;
EditText _txtuser, _txtpass;

2. Initialize the button and text field inside the onCreate() method as:


_btnlogin=(Button)findViewById(R.id.btnlogin);
_txtuser=(EditText)findViewById(R.id.txtuser);
_txtpass=(EditText)findViewById(R.id.txtpass);

3. Create the listning event of the button and write the following code:


_btnlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String user = _txtuser.getText().toString();
String pass = _txtpass.getText().toString();
if(user.equals("admin")&& pass.equals("admin")){
final AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
builder.setTitle("informaiton");
builder.setMessage("username and password matched!");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();

}
}
});

See the design part in video:

SHARE