Edittext輸入數值時做最大最小的限制如0.01到9999.99

方法比較簡單,監聽輸入的數值是否大於或小於指定的值即可,如果大於了,就給edit設置上最大的值,如果小於了就給edit設置最小的值

注意要在xml中指定inputType,不然字符串轉int或者double的時候會出現異常


  1. /** edittext只能輸入數值的時候做最大最小的限制 */  
  2.     public static void setRegion(final EditText edit, final double MIN_MARK, final double MAX_MARK) {  
  3.         edit.addTextChangedListener(new TextWatcher() {  
  4.             @Override  
  5.             public void onTextChanged(CharSequence s, int start, int before, int count) {  
  6.                 if (start > 1) {  
  7.                     if (MIN_MARK != -1 && MAX_MARK != -1) {  
  8.                         double num = Double.parseDouble(s.toString());  
  9.                         if (num > MAX_MARK) {  
  10.                             s = String.valueOf(MAX_MARK);  
  11.                             edit.setText(s);  
  12.                         } else if (num < MIN_MARK) {  
  13.                             s = String.valueOf(MIN_MARK);  
  14.                             edit.setText(s);  
  15.                         }  
  16.                         edit.setSelection(s.length());  
  17.                     }  
  18.                 }  
  19.             }  
  20.   
  21.             @Override  
  22.             public void beforeTextChanged(CharSequence s, int start, int count, int after) {  
  23.             }  
  24.   
  25.             @Override  
  26.             public void afterTextChanged(Editable s) {  
  27.                 if (s != null && !s.equals("")) {  
  28.                     if (MIN_MARK != -1 && MAX_MARK != -1) {  
  29.                         double markVal = 0;  
  30.                         try {  
  31.                             markVal = Double.parseDouble(s.toString());  
  32.                         } catch (NumberFormatException e) {  
  33.                             markVal = 0;  
  34.                         }  
  35.                         if (markVal > MAX_MARK) {  
  36.                             edit.setText(String.valueOf(MAX_MARK));  
  37.                             edit.setSelection(String.valueOf(MAX_MARK).length());  
  38.                         }  
  39.                         return;  
  40.                     }  
  41.                 }  
  42.             }  
  43.         });  
  44.     }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章