How to combine input fiters for numberdecimal Edit

2019-09-11 12:51发布

问题:

I have an app with single numberdecimal EditText. I have done 2 input filters for that EditText. I want to combine these input filters, because one of them isn't working: I want to make that the user cannot enter a value greater than 120.0. Example:

User can input 1, 2.3, 23, 45.7, 89.6, 119.9, 120.0 etc. User can't input 3.34, 45.76, 89.652, 120.00, 121.00 etc.

But this code allow user to enter as many digits before decimal point, as he want:(

Code of my input filters:

    editText.setFilters(new InputFilter[] {new InputFilterMinMax(1,120)});
    editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(1)});

    public class DecimalDigitsInputFilter implements InputFilter {

    private final int decimalDigits;

    /**
     * Constructor.
     *
     * @param decimalDigits maximum decimal digits
     */
    public DecimalDigitsInputFilter(int decimalDigits) {
        this.decimalDigits = decimalDigits;
    }

    @Override
    public CharSequence filter(CharSequence source,
                               int start,
                               int end,
                               Spanned dest,
                               int dstart,
                               int dend) {


        int dotPos = -1;
        int len = dest.length();
        for (int i = 0; i < len; i++) {
            char c = dest.charAt(i);
            if (c == '.' || c == ',') {
                dotPos = i;
                break;
            }
        }
        if (dotPos >= 0) {

            // protects against many dots
            if (source.equals(".") || source.equals(","))
            {
                return "";
            }
            // if the text is entered before the dot
            if (dend <= dotPos) {
                return null;
            }
            if (len - dotPos > decimalDigits) {
                return "";
            }
        }

        return null;
    }

    }

    public class InputFilterMinMax implements InputFilter {

    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            int input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) { }
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
   }

Please, define me how to create a combined filter, that work with edittext as I want