In many applications, it’s necessary to restrict user input to some fix number range like months(1-12), inches(1-12), days(1-30, 1-31), etc. At that time we can use InputFilter to filter the input provided by user.
Let’s start with the XML part.
<EditText android:id="@+id/edt_month" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="month" android:inputType="number" />
Now you need to create on Class for InputFilter with minimum and maximum values.
Here is the class InputFilterMinMax.
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; } }
Now you all set to use this class in your app. Add the following line in your code to apply this.
EditText edtMonth = (EditText) findViewById(R.id.edt_month); edtMonth.setFilters(new InputFilter[]{new InputFilterMinMax("1", "12")});
Download Source Code: https://github.com/dakshbhatt21/a-computer-engineer
what if my range is from 8 to 40 — when i type 13 it wont accept it
Sorry for the late reply, can you please share your code? so I can take a look.