我想创建一个EditText来输入十进制值,允许小数点后2位(可选)。值可以是:
xxxx
xxxx.x
xx.xx
.xx
.x
x.x
我在 S/O 中尝试了很多解决方案,找到了适合我的解决正则表达式。但是没有任何一个满足我的要求。有些方案符合要求,但不允许在小数点前进行编辑。例如,当edittext的值为.xx时,则无法在小数点前(.)进行编辑。
有人能指出合适的解决方案吗?
N.B.:在EditText中使用maxLength属性。
我想创建一个EditText来输入十进制值,允许小数点后2位(可选)。值可以是:
xxxx
xxxx.x
xx.xx
.xx
.x
x.x
我在 S/O 中尝试了很多解决方案,找到了适合我的解决正则表达式。但是没有任何一个满足我的要求。有些方案符合要求,但不允许在小数点前进行编辑。例如,当edittext的值为.xx时,则无法在小数点前(.)进行编辑。
有人能指出合适的解决方案吗?
N.B.:在EditText中使用maxLength属性。
请尝试这个:
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(10, 2) });