I have an AlertDialog with a custom layout (just an EditText) and I want to validate the data when the OK button is clicked. If the validation fails I don't want to close the dialog.
I'm using dialog's default buttons (positive and negative). If I use "setPositiveButton("", new DialogInterface.OnClickListener() ..." the dialog is always closed. I've seen several posts and they said that the onClick Listener should be override, but I can't get it working. This is the code I found:
Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(dialog));
Since it says it should be done AFTER showing the dialog I placed this code inside my activity, not inside my DialogFragment, but if I use mDialogFragment.getDialog() it always returns null.
This is a part of my Dialog Fragment:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.new);
LayoutInflater inflater = getActivity().getLayoutInflater();
dialogView = inflater.inflate(R.layout.edit_license, null);
builder.setView(dialogView)
// Add action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
And in my Activity I do the following:
DialogFragment dialog = new MyDialogFragment(true, null);
dialog.show(getSupportFragmentManager(), "EditLicenseDialogFragment");
AlertDialog alertDialog = (AlertDialog)dialog.getDialog();
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
btnPositive.setOnClickListener(new CustomListener(alertDialog));
...
class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
@Override
public void onClick(View v) {
...
}
}
Like I said, (AlertDialog)dialog.getDialog(); always returns null. Why is that? How can I avoid closing the dialog if the validation is not ok?
Thanks!