![]() |
Custom Alert Dialog Validation |
There are two Dialog that much used, they are AlertDialog and Dialog. Both can used for display a message. You also able to modify the view inside AlertDialog or Dialog. For custom Dialog view, please read here : Android Custom Popup Using AlertDialog And Dialog
Cannot create a validation on EditText inside AlertDialog
My experience using custom alert Dialog is i can't create a validation form and use setError() for EditText. It's because i wrote my validation inside alertDialog.setPositiveButton(). If we need to create a validation, it should outside of that area.
Recommended : Create rating and review look like google play store
Then how to do validation? Here it is, If you need to create a validation inside a custom AlertDialogBuilder, then please use the following code (at least works perfectly in my project):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void showAlertDialog(){ | |
View view = getLayoutInflater().inflate(R.layout.custom_dialog, null); | |
final EditText editTextEmail = (EditText) view.findViewById(R.id.edittext_email); | |
final AlertDialog alertDialog = new AlertDialog.Builder(YourCurrentActivity.this) | |
.setView(view) | |
.setPositiveButton(R.string.lbl_ok, null) | |
.setNegativeButton(R.string.lbl_cancel, null) | |
.create(); | |
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() { | |
@Override | |
public void onShow(DialogInterface dialog) { | |
Button buttonPositive = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE); | |
buttonPositive.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
// Do something when button positive clicked | |
// Your validation is here | |
}); | |
Button buttonNegative = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_NEGATIVE); | |
buttonNegative.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
// Do something when button negative clicked | |
} | |
}); | |
} | |
}); | |
alertDialog.show(); | |
} |
EmoticonEmoticon