If you want to allow only 6 digits before decimal and 2 digits after decimal you no need to add addTextChangedListener
if you want only 8 digit (either
beforeDecimal = 6, afterDecimal = 2 (or) beforeDecimal = 8, afterDecimal = 0 you can use addTextChangedListener
.
EditText tv;
tv = (EditText) findViewById(R.id.test_value);
int beforeDecimal = 6, afterDecimal = 2;
tv.setFilters(new InputFilter[] { new DigitsKeyListener(Boolean.FALSE,
Boolean.TRUE) {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String etText = tv.getText().toString();
if (etText.isEmpty()) {
return null;
}
String temp = tv.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
if (temp.length() > beforeDecimal) {
return "";
}
} else {
int dotPosition;
int cursorPositon = tv.getSelectionStart();
if (etText.indexOf(".") == -1) {
dotPosition = temp.indexOf(".");
} else {
dotPosition = etText.indexOf(".");
}
if (cursorPositon <= dotPosition) {
String beforeDot = etText.substring(0, dotPosition);
if (beforeDot.length() < beforeDecimal) {
return source;
} else {
if (source.toString().equalsIgnoreCase(".")) {
return source;
} else {
return "";
}
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
} });
tv.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String temp = tv.getText() + s.toString();
if (temp.contains(".")) {
beforeDecimal = 6; /***6 Digits beforedecimal and 2 after decimal****/
afterDecimal = 2;
} else {
beforeDecimal = 8; /***8 Digits beforedecimal and 0 after decimal***/
afterDecimal = 0;
}
}