0

我需要 EditText 只允许七个整数和两个十进制数。例如:7777777.99

我在 onTouchListener 事件中尝试使用这个正则表达式,但不起作用。顺便说一句,这是正确的事件吗?

txtRespNumero.addTextChangedListener(new TextWatcher() {
                   int count = 0;    // Declare as Instance Variable
                   boolean isSeven = true; // Declare as Instance Variable

                          public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

                                count++;

                          }

                          public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {


                          }

                          public void afterTextChanged(Editable s) {

                          if(isSeven){
                              if(count == 7){

                                  s.append(".");
                                  isSeven = true;
                              }
                           }

                           if(count < 7){

                               isSeven = true;

                           }

                          }
                      });
4

2 回答 2

1

Try it this way...

- Set the EditText Attribute Max Length as 10.

- Then when you accept the EditeText value, convert it into format of 0000000.00 using the below example:

Eg:

double d = 300.0;
DecimalFormat df = new DecimalFormat("0000000.00");
System.out.println(df.format(d));

/////////////////////////////////// Edited Part /////////////////////////////

Another way to do it, just as you want it.........

int count = 0;    // Declare as Instance Variable
boolean isSix = true; // Declare as Instance Variable

tx = (EditText) findViewById(R.id.editText_CheckIt);

        tx.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

                  count++;

            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {


            }

            public void afterTextChanged(Editable s) {

            if(isSeven){
                if(count == 7){

                    s.append(".");
                    isSeven = true;
                }
             }

             if(count < 7){

                 isSeven = true;

             }

            }
        });
于 2012-11-15T17:30:15.490 回答
0

尝试使用 onTextChanged ,每次用户输入数字时都会调用它(在您的情况下),而不是仅在触摸控件时调用一次)。这个解决方案对我有用: EditText no more than x decimals android

遗憾的是,android 不允许您直接在 XML 中执行此操作。

于 2012-11-15T17:03:48.017 回答