Please look at the custom dialog below. I have an edittext field on the dialog and if the text field is empty I would like to disable the positiveButton
. I can
Here is complete code to enable and disable positive button of dialog:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater layoutInflater = MainActivity.this.getLayoutInflater();
View view = layoutInflater.inflate(R.layout.dialog,null);
builder.setView(view);
builder.setTitle("Test");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Ok clicked", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
builder.setNegativeButton("cancel", null);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
EditText editText = (EditText)view.findViewById(R.id.mobile_number);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if (s.length() >= 1) {
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
} else {
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
}
});