Skip to content

Instantly share code, notes, and snippets.

@aoriani
Created September 5, 2013 02:30
Show Gist options
  • Save aoriani/6445363 to your computer and use it in GitHub Desktop.
Save aoriani/6445363 to your computer and use it in GitHub Desktop.
An Android Input filter that validates the range of an input. The ones on stackoverflow does not seem to understand the meaning of the parameters of the filter method
class RangedInputFilter implements InputFilter {
private int fieldSize;
private int min, max;
RangedInputFilter(int fieldSize, int min, int max) {
this.fieldSize = fieldSize;
if (min > max) {
throw new IllegalArgumentException("Min value should be less or equal to max");
} else {
this.min = min;
this.max = max;
}
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
int dstart, int dend) {
// Compute new string after edition
StringBuilder builder = new StringBuilder(dest);
if (dstart > (dest.length() - 1)) {
builder.append(source);
} else {
builder.replace(dstart, dend, source.toString().substring(start, end));
}
String newString = builder.toString();
// Only valid when input is will be complete as intermediate input
// may be temporally invalid
if (newString.length() == fieldSize) {
try {
int newValue = Integer.parseInt(newString);
if ((min <= newValue) && (newValue <= max)) {
return null; // Accept
} else {
return ""; // Reject
}
} catch (NumberFormatException e) {
return ""; // Reject input
}
} else {
return null; // Accept input
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment