I am using an AlertDialog that is very simple, just a custom view with a text box, and the alertdialog positive submit button. I would like to validate that the text box has had text entered before the user dismisses the dialog. I see two possibilities, with questions about each:
Is either of these options possible with an AlertDialog (vs a custom dialog)?
I think the second option would be the simplest, but I'm up for either if it's possible.
Input Validation, also known as data validation, is the testing of any input (or data) provided by a user or application against expected criteria. Input validation prevents malicious or poorly qualified data from entering an information system.
Input validation is the process of testing input received by the application for compliance against a standard defined within the application. It can be as simple as strictly typing a parameter and as complex as using regular expressions or business logic to validate input.
To inflate the layout in your DialogFragment , get a LayoutInflater with getLayoutInflater() and call inflate() , where the first parameter is the layout resource ID and the second parameter is a parent view for the layout. You can then call setView() to place the layout in the dialog.
I set a TextWatcher to an input field, and then enable the positive button when validation conditions are met. I disable the positive button by default.
AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
final View dialogView = LayoutInflater.from(getSherlockActivity()).inflate(R.layout.create_playlist, null);
final EditText inputField = (EditText) dialogView.findViewById(R.id.edit_newPlaylistName);
... //proceed to setup dialog using builder
final AlertDialog alertDialog = builder.show();
alertDialog.setCanceledOnTouchOutside(true);
final Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setEnabled(false);
inputField.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) {
// my validation condition
if (inputField.getText().length() > 0) {
button.setEnabled(true);
} else {
button.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
The easiest way i think is to defined your own dialog in a xml file. Then you can display it very simple (in this example somewhere in the activity class):
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.your_dialog_file);
Button yourButton = dialog.findViewById(R.id.yourButton);
final EditText text = dialog.findViewById(R.id.yourTextEdit);
yourButton.setOnClickListener( {
public void onClick(View view) {
if ( ! (text.getText().toString.equals(""))) {
//go on here and dismiss dialog
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With