2012-11-15 118 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