I am currently trying to work with AlertDialogs.
Currently, I have an EditText in my AlertDialog, and want to restrict the input to only Integers. I have used a basic try and catch block to avoid the app crashing form a NumberFormatException.
However, I want to set it up so that when the user tries to press the button with the incorrect input, the input does not register and the Dialog is not cancelled.
UpperLimitDialog.setPositiveButton(R.string.Positive_Button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
int RawInput = settings.getInt("UpperLimit", 12);
try {
RawInput = Integer.parseInt(input.getText().toString());
}catch (NumberFormatException se) {
Toast.makeText(SettingsMenu.this, "Non-Integer Value, No Input", Toast.LENGTH_SHORT).show();
//Here I want the app to not register the click and prevent the dialog box from closing.
}
editor.putInt("UpperLimit", RawInput);
editor.apply();
Toast.makeText(SettingsMenu.this, "Set Upper Limit to " + RawInput, Toast.LENGTH_SHORT).show();
}
});
What method can I use to achieve this?
The basic trick here is to use the dialog's setCancelable
to false
and call dismiss()
only when the input has been validated.
More info here: AlertDialog with positive button and validating custom EditText
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments