EditText Values in range

You can assign a TextWatcher to your EditText and listen for text changes there, for example:

public void afterTextChanged(Editable s) {
   try {
     int val = Integer.parseInt(s.toString());
     if(val > 60) {
        s.replace(0, s.length(), "60", 0, 2);
     } else if(val < 1) {
        s.replace(0, s.length(), "1", 0, 1);
     }
   } catch (NumberFormatException ex) {
      // Do something
   }
}

As mentioned by Devunwired, notice that calls to s.replace() will call the TextWatcher again recursively.

It is typical to wrap these changes with a check on a boolean "editing" flag so the recursive calls skip over and simply return while the changes that come from within.


I have come across a neat solution here:

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;
}
}

And simply apply this filter to an edit text like so:

mCentsEditText = (EditText)v.findViewById(R.id.cents_edit_text);
InputFilterMinMax filter = new InputFilterMinMax("0", "99") {};
mCentsEditText.setFilters(new InputFilter[]{filter});

Tags:

Android