In my Android app, I had a need to limit a number in an EditText widget between a certain range. Namely, 0-59, for time entry pertaining to minutes and seconds. Enter Android’s InputFilters, which are an easy and useful way to limit input in an EditText.
First of all, the EditText is defined in the layout XML as follows:
This ensures that the EditText should be a number, of 2 digit length, with initial value “0”.
Then in your code, you’ll need to define an InputFilter as follows:
public class InputFilterMinMax implements InputFilter { private int minimumValue; private int maximumValue; public InputFilterMinMax(int minimumValue, int maximumValue) { this.minimumValue = minimumValue; this.maximumValue = maximumValue; } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { try { int input = Integer.parseInt(dest.subSequence(0, dstart).toString() + source + dest.subSequence(dend, dest.length())); if (isInRange(minimumValue, maximumValue, 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; } }
So now essentially you can define an InputFilter, that initializes with your desired minimum and maximum integer values. It can then be applied to an EditText to limit the entry to a certain range of integer values. So if you have a reference to your EditText in code, for this example it would be initialized in this way:
minsEditText.setFilters(new InputFilter[]{new InputFilterMinMax(0, 59)});
This will limit the entry from 0-59. Of course you can use any number range that you’d like.
Thank you so much! But this is not a godd solution. When “min” value not equal 1, InputFilter not working. For example, when I want range between 18-45, input field not allow me add value less than 18 (for example “1”) and I can’t add 18 or more value