美文网首页
EditText 小数 长度限制

EditText 小数 长度限制

作者: 詹徐照 | 来源:发表于2018-10-29 14:28 被阅读5次

    定义filter

    public class DecimalInputFilter implements InputFilter {
        private final int mDecimalLength;
    
        public DecimalInputFilter(int decimalLength) {
            if (decimalLength < 0) {
                throw new IllegalArgumentException("decimalLength must >= 0");
            }
            mDecimalLength = decimalLength;
        }
    
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            String sourceString = source.toString();
            if (TextUtils.isEmpty(sourceString)) {
                return sourceString;
            }
            CharSequence result = source;
            String destString = dest.toString();
            if (destString.contains(".")) {
                int dotIndex = destString.indexOf(".");
                if (dstart > dotIndex) { // 新输入的内容在小数部分
                    int availableDecimalLength = dotIndex + mDecimalLength + 1 - dest.length();
                    if (availableDecimalLength > 0) {
                        result = source.subSequence(start, start + availableDecimalLength);
                    } else {
                        result = "";
                    }
                }
            }
            return result;
        }
    }
    

    使用filter

    editText.setFilters(new InputFilter[]{new DecimalInputFilter(2)});
    

    相关文章

      网友评论

          本文标题:EditText 小数 长度限制

          本文链接:https://www.haomeiwen.com/subject/veybtqtx.html