2011-04-20 79 views

回答

1
boolean isValid=<EditText Variable>.getText().toString().matches("\\d{2}\\.\\d{2}"); 

將這個方法在onClickListener,我想你會好到哪裏去。

+0

當我嘗試這個正則表達式時,它不匹配它,因爲它需要點而不管數字的位數。使用'\\。?'不夠好,要麼是因爲它允許沒有點的數字。看看我發佈的替代正則表達式。我認爲你的意思是'onKeyListener'。 – Aleadam 2011-04-21 01:44:29

+0

@Aleadam他試圖驗證輸入後輸入,所以我寫onClick,這只是爲了你想要一個像23.45這樣的數字的情況下。表達方式 \\。意味着你正在使用文字。一個正常的。在正則表達式意味着匹配任何字符。 – chaitanya 2011-04-21 03:15:55

+0

我明白'\\。'表達式的含義。我只是比較'\\。'到'\\。?'(即強迫點存在與可選點)。如果您驗證最終字符串,則可以使用表達式,但如果在輸入時驗證它,則不會。 – Aleadam 2011-04-21 04:27:33

7

試試看。我吸取正則表達式,所以它可能不是最好的,但試試看。

EditText text = new EditText(this); 
    InputFilter[] filters = new InputFilter[1]; 
    filters[0] = new InputFilter() { 
     public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
      if (end > start) { 
       String destTxt = dest.toString(); 
       String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend); 
       if (!resultingTxt.matches("^\\d(\\d(\\.\\d{0,2})?)?")) { 
        return ""; 
       } 
      } 
     return null; 
     } 
    }; 
    text.setFilters(filters); 
+1

嗨Aleadam非常感謝你分享你的知識... – praveenb 2011-04-21 18:21:58

相關問題