罗明文
1 天以前 aa512ff5fc428fbee046d6bc0761c3675023769e
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.dollearn.student.utils;
 
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * author:Created by ZHT on 2017/12/25 10:38
 * email:526309416@qq.com
 * desc:输入大小限制
 */
public class NumberInputFilter implements InputFilter {
    Pattern mPattern;
 
    //输入的最大金额
    private static double MAX_VALUE = Integer.MAX_VALUE;
    //小数点后的位数
    private static final int POINTER_LENGTH = 2;
 
    private static final String POINTER = ".";
 
    private static final String ZERO = "0";
 
    public NumberInputFilter(double maxValue) {
        MAX_VALUE = maxValue;
        mPattern = Pattern.compile("([0-9]|\\.)*");
    }
 
    /**
     * @param source 新输入的字符串
     * @param start  新输入的字符串起始下标,一般为0
     * @param end    新输入的字符串终点下标,一般为source长度-1
     * @param dest   输入之前文本框内容
     * @param dstart 原内容起始坐标,一般为0
     * @param dend   原内容终点坐标,一般为dest长度-1
     * @return 输入内容
     */
 
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String sourceText = source.toString();
        String destText = dest.toString();
 
        //验证删除等按键
        if (TextUtils.isEmpty(sourceText)) {
            return "";
        }
 
        Matcher matcher = mPattern.matcher(source);
        //已经输入小数点的情况下,只能输入数字
        if (destText.contains(POINTER)) {
            if (!matcher.matches()) {
                return "";
            } else {
                if (POINTER.equals(source)) {  //只能输入一个小数点
                    return "";
                }
            }
 
            //验证小数点精度,保证小数点后只能输入两位
            int index = destText.indexOf(POINTER);
            int length = dend - index;
 
            if (length > POINTER_LENGTH) {
                return dest.subSequence(dstart, dend);
            }
        } else {
 
            if (!matcher.matches()) {
                return "";
            } else {
                //没有输入小数点的情况下,只能输入小数点和数字,但首位不能输入小数点
                if (POINTER.equals(source) && TextUtils.isEmpty(destText)) {
                    return "";
                }
                //没有输入小数点的情况下,只能输入小数点和数字,但首位为0第二位必须为小数
                if (ZERO.equals(destText) && !source.equals(POINTER)) {
                    return "";
                }
            }
        }
 
        //验证输入金额的大小
        double sumText = Double.parseDouble(destText + sourceText);
        if (sumText > MAX_VALUE) {
            return dest.subSequence(dstart, dend);
        }
 
        return dest.subSequence(dstart, dend) + sourceText;
    }
}