Limit number range in EditText in Android using InputFilter

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s