Skip to content

Instantly share code, notes, and snippets.

@zainalfh
Created February 13, 2025 04:27
Show Gist options
  • Select an option

  • Save zainalfh/9ac82ee662e7ce63ed252f5bbb76849d to your computer and use it in GitHub Desktop.

Select an option

Save zainalfh/9ac82ee662e7ce63ed252f5bbb76849d to your computer and use it in GitHub Desktop.
extension for simple add text change listener and remove it. Generated with GeminiAI
package app.keyboardly.addon.chatgpt
import android.text.Editable
import android.text.TextWatcher
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
/**
* Created by Zainal on 13/02/2025 - 08:57
*/
// resource layout ID Key for storing the TextWatcher as an associated object
private const val TEXT_WATCHER_KEY = R.id.custom_input_layout
// Extension function to add a TextWatcher
fun TextView.addTextChangedListener(
afterTextChanged: ((Editable?) -> Unit)? = null
) {
val watcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
afterTextChanged?.invoke(s)
}
}
// Store the TextWatcher as an associated object
setTag(TEXT_WATCHER_KEY, watcher)
addTextChangedListener(watcher)
}
// Extension function to remove the TextWatcher
fun TextView.removeTextChangedListener() {
// Retrieve the TextWatcher from the associated object
val watcher = getTag(TEXT_WATCHER_KEY) as? TextWatcher
// Remove the TextWatcher if it exists
watcher?.let {
removeTextChangedListener(it)
// Remove the tag
setTag(TEXT_WATCHER_KEY, null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment