Reputation: 778
I have a custom dialog and I want to disable the PositiveButton
if a specific EditText is empty. I couldn't find how to do that on a dialog.
Here is my code :
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_add_apero, null);
builder.setView(view)
.setTitle("Super un nouvel apéro !")
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Ajouter", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String titre_apero = editTextApero.getText().toString();
String date_apero = editTextDate.getText().toString();
listener.applyTexts(titre_apero, date_apero);
}
});
editTextApero = view.findViewById(R.id.edit_apero);
editTextDate = view.findViewById(R.id.edit_date);
return builder.create();
}
So if the field editTextApero
or editTextDate
is empty I want to disable the PositiveButton
or do a pop-up (but it would be a pop-up on a dialog who is also a kind of pop-up) to say that the user has to fill each fields.
Upvotes: 1
Views: 245
Reputation: 603
Just split the builder expression and add the positive button only if your condition is true.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
if(editTextApero.getText().length() != 0) {
builder.setPositiveButton("Ajouter", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String titre_apero = editTextApero.getText().toString();
String date_apero = editTextDate.getText().toString();
listener.applyTexts(titre_apero, date_apero);
}
});
}
EDIT I think this is a possible way:
Set the button disabled to start:
((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
Then set a text change listener to the EditText:
editTextApero.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void afterTextChanged(Editable s) {
if (TextUtils.isEmpty(s)) {
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
} else {
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
}
});
If you want to make it invisible, use instead:
((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setVisibility(View.INVISIBLE);
and to set back
((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setVisibility(View.VISIBLE);
Upvotes: 2