我试图在 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++;
}
}
}
});
最佳答案
试试这个:
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String input = s.toString();
if(input.contains(".") && s.charAt(s.length()-1) != '.'){
if(input.indexOf(".") + 3 <= input.length()-1){
String formatted = input.substring(0, input.indexOf(".") + 3);
editReceiver.setText(formatted);
editReceiver.setSelection(formatted.length());
}
}else if(input.contains(",") && s.charAt(s.length()-1) != ','){
if(input.indexOf(",") + 3 <= input.length()-1){
String formatted = input.substring(0, input.indexOf(",") + 3);
editReceiver.setText(formatted);
editReceiver.setSelection(formatted.length());
}
}
}
请注意,德国小数点是 , 分隔的,而不是 .分开的 如果不需要,您可以删除 else 部分。
关于java - Edittext如何只接受小数点后两位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791818/