Share the post "Android: Set Min & Max Value An EditText Accepts"
Forcing an EditText to accept a number value from a certain range entails the use of filters using the InputFilter class. I created a custom made class that lets you set an EditText to accept only values between a minimum and maximum value.
Here is the class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class InputFilterMinMax implements InputFilter { private int min, max; public InputFilterMinMax(int min, int max) { this.min = min; this.max = max; } public InputFilterMinMax(String min, String max) { this.min = Integer.parseInt(min); this.max = Integer.parseInt(max); } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { try { int input = Integer.parseInt(dest.toString() + source.toString()); if (isInRange(min, max, input)) return null; } catch (NumberFormatException nfe) { } return ""; } private boolean isInRange(int a, int b, int c) { return b > a ? c >= a && c <= b : c >= b && c <= a; } } |
To use the class, do it like this which sets an EditText to accept any number between 1 and 100.
|
1 2 |
EditText et = (EditText) findViewById(R.id.your_edittext); et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "100"); |
There! Now you should be able to have your EditText accept only your desired values. Just be sure you set your EditText widget to accept only numbers.