将“ - ”(减号)添加到CharSequence过滤器方法

时间:2015-12-01 17:53:45

标签: android android-inputtype android-input-filter

我使用的功能允许用户在点前后插入带限制数字的十进制数。我想添加“-”标志,但我没有成功.. 在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 个答案:

答案 0 :(得分:0)

好的..我想通了......我只需要在正确的地方添加减号如下:

    "(([-,1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"