androidandroid-inputtypeandroid-input-filter

add "-" (minus sign) to CharSequence filter method


i m using function that allow the user to insert decimal number with limit digits before and after dot. i want to add to it "-" sign but i didn't succeed.. in xml i set:

 android:inputType="numberDecimal|numberSigned"

But the function prevent from typing minus... here is my code. how to change it in order to allow "-"?

    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;

    }
};

Solution

  • ok..i figured it out... i just had to add the minus in the right place as follow:

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