2012-04-23 63 views
0

其实我有一个EditBox,其中我允许用户输入数字。但我的问题是如何限制用户在小数点之前输入不多于三位数字,小数点后不多于一位数字例如:22.1,333.3,34 ..但如果用户尝试输入6666.777则不会允许他们进入。如何限制用户在编辑框中输入

请帮我解决这个问题。如果可能举例

回答

2

使用InputFilter来限制用户。这是另一个这样的话题。 Limit Decimal Places in Android EditText

修改为您自己。我用这个为我自己。

private class DecimalDigitsInputFilter implements InputFilter 
{ 

    Pattern mPattern; 

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

    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; 
    } 

} 

现在设置过滤器

youEditText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(3,1)}); 
+0

是否可以使用正则表达式做......但什么将是我的条件,模式 – AndroidDev 2012-04-23 10:11:00

+0

是。可能。 :)。编辑我的答案。 – Shaiful 2012-04-23 10:11:30

+0

嘿Shaiful ..你的代码工作,但333后,它不会让我进入。我想要的是让用户在小数点前输入三位数字,在小数点后输入一位数字。在我们的代码中,只有当小数点前有2位数字时,才允许我在小数点后输入数字..但是我的要求是,如果小数点前的数字不超过3位,它总是允许用户在小数点后输入一位数字。更多有史以来它不允许用户输入以零开头的数字,如0.1,0,.1等。 – AndroidDev 2012-04-23 10:30:28

相关问题