我在我的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;
}
與s.toString()完全相同的問題。 – MeesterPatat