[英]How Edittext can accept only two numbers after decimal point
我試圖在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());
}
}
}
請注意,德語小數點是,而不是。 分隔如果不需要,您可以刪除其他部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.