반응형
TextWatcher 를 Utils로 만들어서 따로 관리를 해줄 수 있다. (리사이클러뷰에서 사용해야 할 때 등등 )
https://onlyfor-me-blog.tistory.com/530
[Android] TextWatcher를 공통 클래스로 만드는 방법
앱을 만들면서 editText를 다룰 때 제법 많이 사용하는 것이 TextWatcher라는 인터페이스다. 이것에 대한 설명은 아래 포스팅을 참고하거나 다른 블로그를 먼저 보고 오는 걸 추천한다. https://onlyfor-me-
onlyfor-me-blog.tistory.com
위의 블로그에 잘 나와있다.
class CommonTextWatcher(
private val afterChanged: ((Editable?) -> Unit) = {},
private val beforeChanged: ((CharSequence?, Int, Int, Int) -> Unit) = { _, _, _, _ -> },
private val onChanged: ((CharSequence?, Int, Int, Int) -> Unit) = { _, _, _, _ -> }
) : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
beforeChanged(s, start, count, after)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onChanged(s, start, before, count)
}
override fun afterTextChanged(s: Editable?) {
afterChanged(s)
}
}
사용법 .1
etFirst.addTextChangedListener(CommonTextWatcher(
onChanged = { source, _, _, _ ->
Log.e(TAG, "etFirst - onChanged source : $source")
}
))
etSecond.addTextChangedListener(CommonTextWatcher(
afterChanged = { source ->
Log.e(TAG, "etSecond - afterChanged source : $source")
}
))
사용법 .2
val commonTextWatcher = CommonTextWatcher(
afterChanged = { source ->
Log.e(TAG, "source : $source")
}
)
etFirst.addTextChangedListener(commonTextWatcher)
etSecond.addTextChangedListener(commonTextWatcher)
응용법. (리사이클러뷰를 사용한다는 가정하에 데이터를 TextWatcher 로 가져오고 싶을 때)
class CommonTextWatcher(
private val item : Int
) : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
Timber.d("item: $item")
}
override fun afterTextChanged(s: Editable?) {
}
}
editText.addTextChangedListener(
CommonTextWatcher(
index = item.index,
)
)
반응형
'안드로이드' 카테고리의 다른 글
[Android Studio] 바텀 네비게이션 뱃지 활용하기 (코틀린) (0) | 2024.01.19 |
---|---|
[Android Studio] 뷰 화면 캡쳐하기 (코틀린) (0) | 2023.11.14 |
[Android Studio] TextInputLayout Custom 사용하기 ! (0) | 2023.11.03 |
[Android Studio] TextView Drawable 동적으로 수정하기 (코틀린) (0) | 2023.10.12 |
[Android Studio] Padding 값 동적으로 변경하기 (코틀린) (0) | 2023.09.21 |