Android EditText,格式为十进制值(3,2)

时间:2015-07-01 07:25:29

标签: android android-edittext decimalformat

我搜索了很多但找不到解决问题的方法。 我怎么能有一个editText,用户可以用十进制格式输入数字,格式应该是十进制之前的整数和十进制之后的两个整数。

如果用户输入1,那么它应该是1.00并且不允许输入值grater然后输入9.99。

我已经提到了不同的代码,但没有任何工作。 下面是我的代码 -

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

    }

mSetupProfileViewHolder.mAthleteGPAET.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(3,2)});

但它允许用户输入所有内容,如333,999等。

1 个答案:

答案 0 :(得分:-1)

您想要使用TextWatcher,然后在提交之前检查用户输入的内容。以下是您要实现的代码示例:

final EditText et = (EditText) findViewById(R.id.editText);
et.addTextChangedListener(new TextWatcher() {

   public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {             

   }

   public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {             

   }

   public void afterTextChanged(Editable arg0) {
       if (arg0.length() > 0) {
           String str = et.getText().toString();
           et.setOnKeyListener(new OnKeyListener() {
               public boolean onKey(View v, int keyCode, KeyEvent event) {
                   if (keyCode == KeyEvent.KEYCODE_DEL) {
                       count--;
                       InputFilter[] fArray = new InputFilter[1];
                       fArray[0] = new InputFilter.LengthFilter(100);
                       et.setFilters(fArray);
                       //change the edittext's maximum length to 100. 
                       //If we didn't change this the edittext's maximum length will
                       //be number of digits we previously entered.
                    }
                    return false;
                }
            });
            char t = str.charAt(arg0.length() - 1);
            if (t == '.') {
                count = 0;
            }
            if (count >= 0) {
                if (count == 2) {                        
                    InputFilter[] fArray = new InputFilter[1];
                    fArray[0] = new InputFilter.LengthFilter(arg0.length());
                    et.setFilters(fArray);
                    //prevent the edittext from accessing digits 
                    //by setting maximum length as total number of digits we typed till now.
                }
                count++;
            }
        }
    }
});

上述代码不允许用户在小数点后输入两位以上的数字,您也可以在小数点前输入任意位数。希望这有帮助,如果您有任何问题,请告诉我!

相关问题