I have an Edittext, where I want to allow only numbers and decimal numbers (max 2 decimals after separator e.g. 125.50).
I implemented a filter for this:
final EditText field1 = (EditText)findViewById(R.id.field1);
field1.setFilters(new InputFilter[] { filter });
InputFilter filter = new InputFilter() {
final int maxDigitsBeforeDecimalPoint=5;
final int maxDigitsAfterDecimalPoint=2;
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches(
"(([0-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"
)) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
};
This is working fine, but the problem is, that if user inserts decimal separator ALONE, I've got java.lang.NumberFormatException: For input string: "."
In my ontextChanged I tried this:
if(field1.getText().toString().equals("[.]")){field1.setText(0);}
also this
if(field1.getText().toString().equals(".")){field1.setText(0);}
but did not work.
How can I restrict the decimal separator alone, but allow it with the numbers?