일단기록/간단기록
[안드로이드/android] addTextChangedListener setText 무한루프 해결
겟츄
2022. 6. 7. 18:32
editText의 변화를 감지해 특정 조건을 만족하면 editText를 비어있는 상태로 만들고 싶어 setText(""); 를 했더니 무한 루프에 빠지는 버그가 발생했다. 해결하기 위해 다음과 같은 코드를 추가해 주었다.
binding.pwEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(binding.idEt.getText().length() == 0){
binding.pwEt.removeTextChangedListener(this);
binding.pwEt.setText("");
binding.pwEt.addTextChangedListener(this);
}else{
}
}
idEt에 입력된 text가 없으면 pwEt에 text를 입력해도 지워지는 동작을 구현하였다. 위와같은 코드를 추가하지 않고 setText를 하면 다시 리스너를 불러와 무한루프에 빠지기 때문에 일단 removeTextChangedListner를 이용해 리스너를 지워주고 text를 set 한 다음 다시 listner를 추가해주는 형태로 구현하면 된다.