How to prevent Alertdialog from being closed when a button is clicked?

Asked

Viewed 1,664 times

4

Problem

I’m trying to validate certain data contained in a View customized of a AlertDialog in the Save button click event. Then after the validation I save the data and close the Alertdialog, and in case the data are not valid I would show the errors to be corrected. But even if I don’t call the method dialog.dismiss(); the AlertDialog in question is closed.

Question

How could I intercept and prevent the automatic closing of the AlertDialog by clicking any of its buttons?

Attempt at implementation

What I’m implementing that’s not working is the following:

AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
dialog.setTitle("Preencha o formulário:");
dialog.setCancelable(true);
View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_dialog_forms, null);
dialog.setView(view);
dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.btn_save), new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(validForm()){
            save();
            dialog.dismiss();
        } else {
            exibirErrosFormulario();
            // ... como não chamo "dialog.dismiss();" não era para fechar o AlertDialog, mas está fechando.
        }
    }
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.btn_cancel), new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});
  • Another alternative is http://answall.com/a/85735/5801.

  • @Geisonsantos, which in the end is the same thing, only taking a few more turns, because the secret of the solution is to overwrite the event of clicking the patterns buttons Dialog, like the @ramaral, indicates in his reply.

  • The difference is that I write less, @Fernando. In the end the result is really, yes. It’s more a matter of taste.

1 answer

3


I use a device I found no longer remember where.

Start by defining a class that will treat event onClick dialog button:

public abstract class DialogButtonClickWrapper implements OnClickListener{

    private AlertDialog dialog;

    public DialogButtonClickWrapper(AlertDialog dialog) {
        this.dialog = dialog;
    }

    @Override
    public void onClick(View v) {

        if(onClicked()){
            dialog.dismiss();
        }
    }

    protected abstract boolean onClicked();
}

State the button in the usual way, but do not enter any code in the onClick():

dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.btn_save), new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});

On the line where dialog.show() enter the following code:

//É necessário porque os botões só são atribuídos após o método `show` ser chamado
dialog.show();

Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new DialogButtonClickWrapper(dialog) {

    @Override
    protected boolean onClicked() {

        if(validForm()){
            save();
            return true;//Retornando true fecha o dialog
        } else {
            exibirErrosFormulario();
            return false;//Retornando false o dialog não é fechado
        }
    }
});

The class DialogButtonClickWrapper has only the minimum necessary for this situation.
From it you can improve it to, for example, be it to validate the form and only then call the method onClicked.

Then the class would have a method private boolean isValid() who will return true or false depending on the validity of the form data.
The method onClick would be so:

@Override
public void onClick(View v) {

    if(isValid()){
        if(onClicked()){
            dialog.dismiss();
        }
    }
}

The implementation of the method onClicked will have the code corresponding to the action of the button, must return true if all goes well or false if anything goes wrong.

  • I just tested it here and it works perfectly, thank you very much for the help, I was outraged that this was not possible. Hehe Obs: I edited your post correcting some errors in the syntax, which I checked when implementing here. Make sure I did nothing wrong. = D

  • Other alternative: http://answall.com/a/85735/5801.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.