2013-11-27 57 views
0

我在我的Edittext中添加了一個textchangelistener,其中我檢查文本是否爲空。當文本不爲空時,我按下退格鍵,所有文本消失並再次出現。這隻會在第一次按下退格鍵時發生。之後它就像它應該那樣工作。在TextWatcher中的editText.getText()。toString()在第一個textchange返回空字符串

使用可編輯的s.toString()不能解決問題。

是什麼導致了這個問題?

看到在代碼中的註釋瞭解更多信息:

TextWatcher textwatcher = getMandatoryTextWatcher(editText); 
String text = editText.getText().toString();//At this point String text is not empty. 

editText.addTextChangedListener(textwatcher); 

public TextWatcher getMandatoryTextWatcher(final EditText editText) { 
    TextWatcher textwatcher = new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
      //To change body of implemented methods use File | Settings | File Templates. 
     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      //To change body of implemented methods use File | Settings | File Templates. 
     } 

     @Override 
     public void afterTextChanged(Editable s) { 
      try { 
       //The first time this is called(the first softkey backspace press), 
       //text is empty. This causes a weird issue where the character that 
       //was just removed by pressing the backspace, reappears again. 
       //This is only the first time. 

       String text = editText.getText().toString(); 

       if (text.length() <= 0) { 
        editText.setError(errorMandatory); 

       } else if (text.length() > 0) { 
        editText.setError(null); 
       } else { 
        editText.setError(errorMelding); 
       } 
      } catch (NumberFormatException nfe) { 
        editText.setError(errorMeldingTijdensParsen); 
     } 
    } 
}; 
return textwatcher; 
} 

回答

0

樂施會的傢伙只要給這個驗證一個第一次

if(TextUtils.isEmpty(Stringname)) 
{ 
    paste your rest code here 
} 

所以每當它第一次也不會在條件

0

將您的代碼複製到onTextChanged並將您的代碼放入以下語句中:

if (s.length() > 0) 
    { 
    // do what you want 
    } 
0

你最好使用s.toString();代替editText.getText().toString();

+0

與s.toString()完全相同的問題。 – MeesterPatat

0

我編譯你的代碼分鐘。 sdk 10(2.3.3)和目標sdk 14(4.0)。 在三星GT-P6800設備中運行它,報告的行爲不會發生。 您的問題可能在代碼之外。嘗試在另一個設備上運行你的代碼。

相關問題