Validation on EditText in alertDialog

10,228

Solution 1

This answer is compiled from Android Dialog, keep dialog open when button is pressed.

As written in Dismissing Dialog API Guide,

When the user touches any of the action buttons created with an AlertDialog.Builder, the system dismisses the dialog for you.

So you need to make a custom click listener for prevent the dialog being closed.

First Way
You can prevent the positive button from closing the dialog. You basically need to:

  1. Create the dialog with DialogBuilder
  2. show() the dialog
  3. Find the buttons in the dialog shown and override their onClickListener

So, create a listener class:

class CustomListener implements View.OnClickListener {
  private final Dialog dialog;

  public CustomListener(Dialog dialog) {
    this.dialog = dialog;
  }

  @Override
  public void onClick(View v) {
    // Do whatever you want here

    // If you want to close the dialog, uncomment the line below
    //dialog.dismiss();
  }
}

Then when showing the dialog use:

AlertDialog dialog = dialogBuilder.create();
dialog.show();
Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(dialog));

Remember, you need to show the dialog otherwise the button will not be findable. Also, be sure to change DialogInterface.BUTTON_POSITIVE to whatever value you used to add the button. Also note that when adding the buttons in the DialogBuilder you will need to provide onClickListeners - you can not add the custom listener in there, though - the dialog will still dismiss if you do not override the listeners after show() is called.

Second Way

Here is an example of the same approach using an anonymous class instead so it is all in one stream of code:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
AlertDialog dialog = builder.create();
dialog.show();

//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {            
     @Override
     public void onClick(View v) {
       boolean wantToCloseDialog = false;

       //Do stuff, possibly set wantToCloseDialog to true then...
       if(wantToCloseDialog)
          dismiss();
       //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
       }
    });

Solution 2

This is how to validate input password inside AlertDialog.

Make sure you have created an individual xml layout file for the password which has only one component/view that is EditText to get the password from the user.

After creating a layout for input password, we will inflate the layout with Dialog as to set our custom view to the AlertDialog.

Inflater inflater = new Inflater(this);
View myPasswordView = inflater.inflate(R.xml.my_custom_password_layout);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Password");
//alertDialogBuilder.setMessage("Enter password to open Application.");
alertDialogBuilder.setView(myPasswordView);

alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                // Do not use this place as we are overriding this button later in the cade.
            }
        }); alertDialogBuilder.setPositiveButton("Cancel", 
        new DialogInterface.OnClickListener({
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                // Dismiss dialog and close activity if appropriated, do not use this (cancel) button at all. 
                dialog.dismiss();
            }
        });

final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
// Overriding the that button here immediatly handle the user's activity.
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
      {            
          @Override
          public void onClick(View v)
          {
              Boolean isError = false;
              //Do your job here. For example we are checking the input password.
              final EditText txtPassword = myPasswordView.findViewById(R.id.txtPassword);
              String password = txtPassword.getText().toString().trim();
              Boolean isError = true;

              // Check password if not empty. You can add another IF statement to do your logic for password validation.
              if(password.isEmpty()) {
                  isError = true;
                  txtPassword.setError("Password cannot be empty");
              }
              if(password.equals("1234") {
                  // You password is correct. 
                  isError = false;
                  txtPassword.setError(null);
              }
              if(!isError)
                  dialog.dismiss();
              // Otherwise the dialog will stay open.
          }
      });
Share:
10,228
Kiran Malvi
Author by

Kiran Malvi

Android Developer by profession, passionate for development. I like to see and experience the process of bringing new, innovative ideas to reality . Working at Spiritus Payments, and in free time work on some of my ideas. Biking, trekking and solo traveling is next thing I love.

Updated on June 18, 2022

Comments

  • Kiran Malvi
    Kiran Malvi almost 2 years

    I am trying to add empty field validations on EditText on AlertDialog. But even after field is empty error message is not getting displayed, instead AlertDialog is closing. But if conditions are working well as I'm not able to do post operations if any of the field is empty.

    Here is my Java Sample code:

    public class TourActivity extends AppCompatActivity {
    
    private LayoutInflater inflater;
    private FloatingActionButton fab;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tour);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        fab = (FloatingActionButton) findViewById(R.id.fab);
    
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inflater = TourActivity.this.getLayoutInflater();
                View content = inflater.inflate(R.layout.activity_add_new_trip, null);
                final EditText editEvent = (EditText) content.findViewById(R.id.edTxt_EventName);
                final EditText editStartDate = (EditText) content.findViewById(R.id.edTxt_EventSDate);
    
    
                AlertDialog.Builder builder = new AlertDialog.Builder(TourActivity.this);
                builder.setView(content)
                        .setTitle("Add Event")
                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
    
                                        editEvent.setError(null);
                                        editStartDate.setError(null);
    
                                        boolean cancel = false;
                                        View focusView = null;
    
                                        if (TextUtils.isEmpty(editEvent.getText().toString()))) {
                                            editEvent.setError("Please Enter Event Name.");
                                            return;
                                        }
    
                                        if (TextUtils.isEmpty(editStartDate.getText().toString())) {
                                            editStartDate.setError("Please Enter Event Start Date.");
                                            focusView = editStartDate;
                                            cancel = true;
                                        }
    
    
                                        if (cancel == true) {
                                            Snackbar.make(findViewById(android.R.id.content),
                                                    "Event Unsuccessful.", Snackbar.LENGTH_LONG)
                                                    .setActionTextColor(Color.RED)
                                                    .show();
                                            focusView.requestFocus();
                                        } else {
                                            // Some action here
                                        }
                                    }
                                })
                        .setNegativeButton(cancel, new DialogInterface.OnClickListener() {
    
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
    }
    }