3

How do i make custom validations in appcompact7 alertdialog? I have some inputs in my alertdialog, so when i click the positive button, i want to validate if the condition is true, in case the condition returns false i just want to show error message and dialog shouldn’t get dismissed.

tried this, didnt help

alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (true) {
                                    // Do this and dissmiss
                                } else {
                                    // Do not dismiss the dialog
                                    errormsg.setVisibility(View.VISIBLE);
                                    errormsg.setText("Error");
                                }

                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
Community
  • 1
  • 1
Veer3383
  • 1,785
  • 6
  • 29
  • 49

1 Answers1

1

Do not add the click listener in the builder. Add the listener inside onShow() or onStart() of the dialog.

builder.setPositiveButton("Proceed", null);

@Override
    public void onStart() {
        super.onStart();
        final AlertDialog dialog = (AlertDialog) getDialog();

         if (dialog != null) {
            Button positiveButton = dialog.getButton(Dialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
        }
    }
Ankit Aggarwal
  • 5,317
  • 2
  • 30
  • 53