admin
2021-05-08 f93ff67ed4681f416a653370aa1e7995a56940ef
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.wpc.library.util;
 
import android.text.InputFilter;
import android.text.Spanned;
 
/**
 * Edittext  小数点后输入位数限制
 */
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 "";
            }
        } else {
            if (dest.length() >= 1 && dest.charAt(0) == '0' && !source.equals(".")) {
                return "";
            }
        }
 
        return null;
    }
}