2012-11-15 119 views
0

我需要的EditText允许只有七个整数和两个小数。例如:7777777.99只允许两位小数输入EDITTEXT

我尝试用这个表达式,在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; 

          } 

          } 
         }); 

回答

0

尝试onTextChanged相反,它得到每次叫用户输入NUMER(在你的情况),而不是只有一次当控制被触摸)。此解决方案为我工作: EditText no more than x decimals android

很遗憾,android不允许你直接在XML中做这个。

+0

我尝试用这种解决方案,但应用程序是错误和关闭时,输入的第一个数字......看到问题更新最多... – ale

1

试试这样...

-设置EditText属性Max Length为10

-然后,当你接受EditeText值,使用下面将其转换成格式的0000000.00例如:

例如:

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

///////////////////////////////////编辑部分//////// /////////////////////

另一种方式来做到这一点,就像你想要它.........

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; 

      } 

      } 
     }); 
+0

最好试试我的编辑部分 –

+0

你是什么意思与“标为实例变量”? ?该IDE ---->说: – ale

+0

维韦克·库马尔·米特拉“最后的局部变量isSeven无法分配,因为它是在一个封闭的类型定义”,见向上请 – ale