I want to define a min and max value for an EditText
.
For example: if any person tries to enter a month value in it, the value must be between 1-12.
Extension of Pratik's and Zac's answer. Zac fixed a small bug of Pratik's in his answer. But I notcied that code doesn't support negative values, it will throw a NumberFormatException. To fix that, and allow the MIN to be negative, use the following code.
Add this line (In bold) between the other two lines:
newVal = newVal.substring(0, dstart) + source.toString()+ newVal.substring(dstart, newVal.length());
if(newVal.equalsIgnoreCase("-") && min < 0)return null;
int input = Integer.parseInt(newVal);
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
// Remove the string out of destination that is to be replaced
String newVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend, dest.toString().length());
// Add the new string in
newVal = newVal.substring(0, dstart) + source.toString() + newVal.substring(dstart, newVal.length());
//****Add this line (below) to allow Negative values***//
if(newVal.equalsIgnoreCase("-") && min < 0)return null;
int input = Integer.parseInt(newVal);
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
return "";
}