2014-10-02 35 views
2

我有一個EditText並有一個TextWatcher它。使用TextWatcher檢測刪除的最後文本

我在其中輸入數字,如果最後一個文本被刪除,我想用0填充該字段。

我該如何使用TextWatcher這三種方法?

input.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
     } 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 
     } 

     @Override 
     public void afterTextChanged(Editable s) { 
      double value=Double.parseDouble(input.getText().toString());//here it will throw error if no text there. 
      //I do not only want to catch this exception and do something with it, but I want to detect this event and if it happens I want to try some solution to stop it. 
     } 
    }); 
+0

檢查,如果S的長度等於0,或者如果s爲null – 2014-10-02 05:10:06

回答

2

in afterTextChanged方法...如果塊看到它是否爲空。此外,而不是使用輸入編輯框使用您在方法參數中具有的編輯。

if (s.toString()!=null && s.toString().trim().equals("")==false){ 
    double value=Double.parseDouble(s.getText().toString()); 
}else{ 
    double value = 0; 
} 
0

你可以這樣做:在ontextchanged

@Override 
    public void afterTextChanged(Editable s) { 
     try { 
      double value=Double.parseDouble(s.toString()); 
      ... //if there is something to do with value 
     } catch (NumberFormatException e) { 
      s.clear(); 
      s.insert(0, "0"); 
      // The method will be recalled since s was changed 
     } 
    }