在 CharSequence 过滤方法中添加“-”(减号)
add "-" (minus sign) to CharSequence filter method
我正在使用允许用户在点前后插入具有限制数字的十进制数的功能。我想给它添加“-
”标志,但我没有成功..
在 xml 我设置:
android:inputType="numberDecimal|numberSigned"
但是函数阻止输入减号...这是我的代码。如何更改它以允许“-
”?
InputFilter filter = new InputFilter() {
final int maxDigitsBeforeDecimalPoint=10;
final int maxDigitsAfterDecimalPoint=2;
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches(
"(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"
)) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
};
好的..我想出来了...我只需要在正确的地方添加减号如下:
"(([-,1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"
我正在使用允许用户在点前后插入具有限制数字的十进制数的功能。我想给它添加“-
”标志,但我没有成功..
在 xml 我设置:
android:inputType="numberDecimal|numberSigned"
但是函数阻止输入减号...这是我的代码。如何更改它以允许“-
”?
InputFilter filter = new InputFilter() {
final int maxDigitsBeforeDecimalPoint=10;
final int maxDigitsAfterDecimalPoint=2;
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches(
"(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"
)) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
};
好的..我想出来了...我只需要在正确的地方添加减号如下:
"(([-,1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"