EditText에 입력한 값을 실시간으로 관찰하면서 입력값에 따른 활동을 처리해야 할 때가 있다.
이때 가볍게 쓸 수 있는 편리한 TextWatcher
란 인터페이스가 있다.
TextWatcher 말 그대로 텍스트를 지켜 보고 있는 인터페이스이다.
인터페이스기 때문에 구현하면 TextWatcher가 갖고 있는 모든 메서드를 재정의해야 하는데, TextWatcher에는 3가지 메서드가 있다.
자세한 내용은 공식문서 참고
<EditText
android:id="@+id/et_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
... />
<Button
android:id="@+id/btn_complete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
... />
간단하게 위와같이 나타내겠다.
나는 binding을 사용하여 바로 작성하였다.
binding.etTitle.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// text가 변경되기 전 호출
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//text가 바뀔 때마다 호출
if (binding.etTitle.length() > 0) {
binding.btnComplete.setBackgroundResource(R.drawable.background_add_btn_active);
} else {
binding.btnComplete.setBackgroundResource(R.drawable.background_add_btn_default);
}
}
@Override
public void afterTextChanged(Editable s) {
// text가 변경된 후 호출
}
});
beforeTextChanged
에서 CharSequences
에는 변경 전 문자열이 담겨 있다.
onTextChanged
에서 CharSequences
에는 변경 될 때마다 호출
afterTextChanged
에서 CharSequences
에는 변경 후의 문자열이 담겨 있다.
변경되는 즉시 호출하기 위해 onTextChange
를 사용하였다.
onTextChange 안에 코드를 살펴보자
binding.etTitle.length() > 0
EditText의 값이 변경될 때 길이가 0 보다 크다면 버튼 drawable을 background_add_btn_active로 적용시키고, 변경된 값의 길이가 0 보다 크지 않다면 background_add_btn_default를 적용시켜준다는 뜻이다.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/btn_active" />
<stroke
android:width="1dp"
android:color="@color/btn_active" />
<corners
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#DADADA" />
<stroke
android:width="1dp"
android:color="#DADADA" />
<corners
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp" />
</shape>