2017-10-07 90 views
0

我想用特定值(不是最大長度)限制EditText條目。

示例 - MaxValue是$ 100。

可能的最高值輸入 100,100.0,100.00

所以我不能與最大長度限制它。

是否可以限制用戶輸入值的時間?

或檢查值if(edittextvalue>100)TextChangeListener是唯一的選擇嗎?

+0

在TextWatcher中檢查是唯一的方法。 –

回答

0

是否可以限制用戶輸入值?

是的,您應該使用TextWatcher。我希望這是最好的方式。

當一個類型的對象附加到可編輯時,當文本被更改時,將調用其方法 。

private final TextWatcher TxtWatecherExample= new TextWatcher() { 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

     } 

     public void onTextChanged(CharSequence s, int start, int before, int count) { 
     // Add your LOGIC 
      if() 
      {} 
      else 
      {} 
     } 

     } 

     public void afterTextChanged(Editable s) { 

    }; 

onTextChanged

無效onTextChanged(CharSequence中, INT開始, INT之前, 詮釋計數)這個方法被調用來通知您,S中,計從開始處開始的字符剛剛替換了以前長度爲 的舊文本。嘗試從此回調中對 進行更改是錯誤的。

+0

Downvoting。這個答案沒有給任何解決方案。 op已經從'TextChangeListener'知道了它。 –

0

addTextChangedListener事件添加到您的editText

這樣。

 editText.addTextChangedListener(new TextWatcher() { 
      @Override 
      public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { 

      } 

      @Override 
      public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { 
       try { 
        double value = Double.parseDouble(editText.getText().toString()); 
        if (value >= 100.0) { 
         // Your code goes here. 
        } else { 
         // Your code goes here. 
        } 
       } catch (Exception ex) { 
        // Handle empty string. Since we're passing the edittext value. 
       } 
      } 

      @Override 
      public void afterTextChanged(Editable editable) { 

      } 
     }); 

希望這會有所幫助。