美文网首页
限制输入小数位数

限制输入小数位数

作者: AnthZh | 来源:发表于2017-01-03 17:30 被阅读16次
    public class DecimalDigitsFilter implements InputFilter {
        private int maxDigits;
        private SpannableStringBuilder spannableStringBuilder;

        DecimalDigitsFilter(int maxDigits) {
            this.maxDigits = maxDigits;
            spannableStringBuilder = new SpannableStringBuilder();
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            spannableStringBuilder.clear();
            spannableStringBuilder.append(dest.toString());
            spannableStringBuilder.insert(dstart, source.toString());

            String numValue = spannableStringBuilder.toString();
            if (!numValue.contains(".")) return null;
            int dotIndex = numValue.indexOf(".") + 1;

            int digits = numValue.substring(dotIndex).length();
            if (digits > maxDigits) {
                return "";
            }
            return source;
        }
    }

相关文章

网友评论

      本文标题:限制输入小数位数

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