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.
//still has some problem but Here you can use min, max at any range (positive or negative)
// in filter calss
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
// Remove the string out of destination that is to be replaced
int input;
String newVal = dest.toString() + source.toString();
if (newVal.length() == 1 && newVal.charAt(0) == '-') {
input = min; //allow
}
else {
newVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend, dest.toString().length());
// Add the new string in
newVal = newVal.substring(0, dstart) + source.toString() + newVal.substring(dstart, newVal.length());
input = Integer.parseInt(newVal);
}
//int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {
}
return "";
}
//also the filler must set as below: in the edit createview
// to allow enter number and backspace.
et.setFilters(new InputFilter[]{new InputFilterMinMax(min >= 10 ? "0" : String.valueOf(min), max >-10 ? String.valueOf(max) :"0" )});
//and at same time must check range in the TextWatcher()
et.addTextChangedListener(new
TextWatcher() {
@Override
public void afterTextChanged (Editable editable)
{
String tmpstr = et.getText().toString();
if (!tmpstr.isEmpty() && !tmpstr.equals("-") ) {
int datavalue = Integer.parseInt(tmpstr);
if ( datavalue >= min || datavalue <= max) {
// accept data ...
}
}
}
});