Created
October 8, 2015 07:53
-
-
Save a11n/45975716f878f1e81804 to your computer and use it in GitHub Desktop.
Limiting the range of numbers in EditTexts
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
public class NumberRangeInputFilter implements InputFilter { | |
private final int min; | |
private final int max; | |
public NumberRangeInputFilter(int min, int max) { | |
this.min = min; | |
this.max = max; | |
} | |
@Override | |
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, | |
int dend) { | |
String text = buildString(source.toString(), dest.toString(), dstart, dend); | |
try { | |
int value = Integer.valueOf(text); | |
if (value > max) { | |
return String.valueOf(max); | |
} else if (value < min) { | |
return String.valueOf(min); | |
} else { | |
return null; | |
} | |
} catch (NumberFormatException e) { | |
return String.valueOf(min); | |
} | |
} | |
private String buildString(String source, String dest, int dstart, int dend) { | |
String previousPart = dest.substring(0, dstart); | |
String nextPart = dest.substring(dend); | |
return previousPart + source + nextPart; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment