【发布时间】:2012-10-06 06:34:40
【问题描述】:
我在列表视图中有编辑文本。如果用户在小数点后输入超过两位数,我想限制用户。现在它允许 n 个数字。如何限制用户在不使用模式的情况下输入的小数点后不超过两个数字?
【问题讨论】:
标签: android decimal restriction
我在列表视图中有编辑文本。如果用户在小数点后输入超过两位数,我想限制用户。现在它允许 n 个数字。如何限制用户在不使用模式的情况下输入的小数点后不超过两个数字?
【问题讨论】:
标签: android decimal restriction
您可以使用TextWatcher 并在afterTextChanged 方法中使用正则表达式来匹配所需的文本并删除输入的额外数字。
【讨论】:
我们可以如下使用正则表达式(regex):
public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Matcher matcher=mPattern.matcher(dest);
if(!matcher.matches())
return "";
return null;
}
}
要使用它:
editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
【讨论】:
可能已经晚了,但我正在发布我的解决方案,希望它对某人有用
在您的文本观察方法 afterTextChanged 中执行此操作。
public void afterTextChanged(Editable s) {
if(mEditText.getText().toString().contains(".")){
String temp[] = mEditText.getText().toString().split("\\.");
if(temp.length>1) {
if (temp[1].length() > 3) {
int length = mEditText.getText().length();
mEditText.getText().delete(length - 1, length);
}
}
}
}
【讨论】: