I want to define a min and max value for an EditText.
For example: if any person tries to enter a month value in it, the value must be between 1-12.
@Pratik Sharma
For support negative numbers, add the following code within the filter method:
package ir.aboy.electronicarsenal;
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMinMax implements InputFilter {
private int min, max;
int input;
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 {
if ((dest.toString() + source.toString()).equals("-")) {
source = "-1";
}
input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException ignored) {
}
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
Then use this from your Activity :
findViewById(R.id.myEditText).setFilters(new InputFilter[]{ new InputFilterMinMax(1, 12)});
Set your edittext with:
android:inputType="number|numberSigned"