본문 바로가기
안드로이드

[Android Studio] TextWatcher Utils 로 사용하기 (코틀린)

by 개발_블로그 2023. 11. 3.
반응형

 

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,
    )
)
반응형