我试图在小数点输入后仅添加两个数字EditText
。
所以我实现了一个TextWatcher
来检查string
输入期间。
我在下面使用的功能效果惊人,但有一个主要缺陷。当您输入任何值时,添加一个小数点,删除该小数点并继续添加更多值,仅接受 3 个值作为输入。
案例示例:我输入300.
但后来我意识到我想输入3001234567
,所以我删除了小数点.
并继续添加1234567
到300
,只有123
将被接受,其余的被忽略。
我该如何处理?任何建议将不胜感激。
我的代码:
price.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
if (arg0.length() > 0) {
String str = price.getText().toString();
price.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
count--;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(100);
price.setFilters(fArray);
//change the edittext's maximum length to 100.
//If we didn't change this the edittext's maximum length will
//be number of digits we previously entered.
}
return false;
}
});
char t = str.charAt(arg0.length() - 1);
if (t == '.') {
count = 0;
}
if (count >= 0) {
if (count == 2) {
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(arg0.length());
price.setFilters(fArray);
//prevent the edittext from accessing digits
//by setting maximum length as total number of digits we typed till now.
}
count++;
}
}
}
});