0

May i know how to avoid AlertDialog to close even when i click the OK.

The reason for this is to make a simple error handling when there is a wrong input.

------------------------
Input password
------------------------

Password:______________

_______________________
   | OK |  | Cancel|

I want this dialog to remain when there is wrong input. so that the user can input again.

My code:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Insert Passcode");
                    final EditText input = new EditText(this);
                    input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    builder.setView(input);

                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            m_Text = input.getText().toString() ;
                            if (m_Text.equals(String.valueOf(passcode_value))){
                                btnAutoLogin.performClick();
                            }
                            else
                            {
                                  xxxxxxxxxxxxxxx
                            }
                        }
                    });
                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });

                    builder.show();
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
enzo
  • 309
  • 3
  • 15

2 Answers2

1

Yes, you can simply override positive button functionality like this:-

builder.setPositiveButton("OK", null);
    AlertDialog dialog = builder.create();
    dialog .show();
    dialog .getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
          // implement your code here
    });
cool Boy
  • 326
  • 1
  • 2
  • 9
0

Create the Custom Listener Class First for Button Click Event as follows:

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 tou want to close the dialog, uncomment the line below
    //dialog.dismiss();
}

}

And when You are showing the Dialog or initialize the Dialog Button as follows :

AlertDialog dialog = dialogBuilder.create();
dialog.show();
Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
button.setOnClickListener(new CustomListener(dialog));
Rajan Bhavsar
  • 1,977
  • 11
  • 25