如何长的EditText限制到7整数和2位小数? [英] How to limit EditText length to 7 integers and 2 decimal places?

查看:277
本文介绍了如何长的EditText限制到7整数和2位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要允许用户高达7个数字和小数点后两位输入的EditText 框。进入七位数字后,不应该允许增加一个数字,但我可以允许高达2位小数。我用了2个小数位小数过滤器,并在此XML code

I have an EditText box which have to allow user to enter upto 7 numbers and two decimal places. After entering seven digits,it should not allow to add one more digit but i may allow upto 2 decimal places. I use a decimal filter for 2 decimal places and this code in XML

android:maxLength="7"    
android:imeOptions="actionDone"                  
android:inputType="numberDecimal"

的EditText 被允许输入 8位数字。这该如何解决呢?

But EditText is allowing to enter 8 digits. How can this be solved?

推荐答案

的onCreate下试试这个

 youreditText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,1)});

这在任何地方你的程序

   public class DecimalDigitsInputFilter implements InputFilter {

        Pattern mPattern;

        public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
            mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
        }

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

                Matcher matcher=mPattern.matcher(dest);       
                if(!matcher.matches())
                    return "";
                return null;
            }

        }

这篇关于如何长的EditText限制到7整数和2位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆