Ad

How To Handle Empty Text From The Input Alert Dialog And Control The Alert Button

I have an alert dialog and I have an input from the alert dialog. The current issue is I cant handle the input from the alert dialog if the user didnt input any text and click ok button. How to set the textfield showing error if user didnt input any text and click OK button and without closing the alert dialog. Below is my code.

 final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setTitle("Save QR Code");
    builder.setMessage("Please enter the name for the QR Code.");
    builder.setCancelable(true);

    // Set up the input
    final EditText input = new EditText(getContext());
    input.setInputType(InputType.TYPE_CLASS_TEXT );
    builder.setView(input);

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // Here is the part
            m_Text = input.getText().toString().trim();
            if(TextUtils.isEmpty(m_Text)){
                input.setError("Please Enter Name of the Image QR Code");
            }else {
                //do smtg
            }
        }
    });
    builder.show();
Ad

Answer

You should set the listener later:

final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setTitle("Save QR Code");
    builder.setMessage("Please enter the name for the QR Code.");
    builder.setCancelable(true);
// Set up the input
final EditText input = new EditText(getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT );
builder.setView(input);

builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.show();
Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(view1 -> { 
        m_Text = input.getText().toString().trim();
        if(TextUtils.isEmpty(m_Text)){
            input.setError("Please Enter Name of the Image QR Code");
        } else {
            dialog.dismiss();
        }
});

The problem with your approach is that AlertDialog will still use its listener as a kind of decorator of yours. So it will call your listener but then it will still close the dialog. If you want to prevent it, you need to overwrite the internal listener with yours after the dialog is shown.

Ad
source: stackoverflow.com
Ad