Skip to content

Instantly share code, notes, and snippets.

@ElianFabian
Last active May 11, 2024 18:06
Show Gist options
  • Save ElianFabian/ef1c2460fa5c1626bbd45a47dfde6d60 to your computer and use it in GitHub Desktop.
Save ElianFabian/ef1c2460fa5c1626bbd45a47dfde6d60 to your computer and use it in GitHub Desktop.
TextView extension functions to easily implement reactivity.
import android.widget.TextView
import androidx.core.widget.doAfterTextChanged
// Source: https://stackoverflow.com/questions/9385081/how-can-i-change-the-edittext-text-without-triggering-the-text-watcher
/**
* Whenever the user makes a change to the text
* the action parameter will be triggered.
*
* This function is meant to be used with [setTextIfDistinct]
* to avoid triggering the action if the text hasn't changed from user input.
*/
inline fun TextView.onTextChanged(
crossinline action: (String) -> Unit,
) {
doAfterTextChanged {
if (hasFocus()) {
action(it.toString())
}
}
}
/**
* Sets the text only if is distinct.
*
* This is useful to avoid triggering the action if the text hasn't changed from user input.
*
* This extension function is meant to be used with [onTextChanged].
*/
fun TextView.setTextIfDistinct(text: String?) {
val hasFocus = hasFocus()
if (hasFocus) {
clearFocus()
}
if (this.text.toString() != text) {
this.text = text
}
if (hasFocus) {
requestFocus()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment