【发布时间】:2015-03-16 10:46:20
【问题描述】:
我有一个编辑文本,我想控制它。输入类型是 numberDecimal,我想写这样的验证。我想在小数点前应该是 0> 并且最大 10 和小数点后 0 > 最大 2 个数字 我搜索并找到了一些 InputFilter 示例。
edittext.setFilters(new InputFilter[] { new DigitsKeyListener(
Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 10, afterDecimal = 2;
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String etText = edittext.getText().toString();
String temp = edittext.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
int dotPosition ;
int cursorPositon = edittext.getSelectionStart();
if (etText.indexOf(".") == -1) {
Log.i("First time Dot", etText.toString().indexOf(".")+" "+etText);
dotPosition = temp.indexOf(".");
Log.i("dot Positon", cursorPositon+"");
Log.i("dot Positon", etText+"");
Log.i("dot Positon", dotPosition+"");
}else{
dotPosition = etText.indexOf(".");
Log.i("dot Positon", cursorPositon+"");
Log.i("dot Positon", etText+"");
Log.i("dot Positon", dotPosition+"");
}
if(cursorPositon <= dotPosition){
Log.i("cursor position", "in left");
String beforeDot = etText.substring(0, dotPosition);
if(beforeDot.length()<beforeDecimal){
return source;
}else{
if(source.toString().equalsIgnoreCase(".")){
return source;
}else{
return "";
}
}
}else{
Log.i("cursor position", "in right");
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
} });
但我不知道解决方案。
【问题讨论】:
标签: android android-edittext android-inputtype android-input-filter