Last active
August 28, 2024 13:30
-
-
Save ElianFabian/ef1c2460fa5c1626bbd45a47dfde6d60 to your computer and use it in GitHub Desktop.
TextView extension functions to easily implement reactivity.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.view.View | |
import android.widget.ScrollView | |
fun ScrollView.smoothScrollToViewBottom(view: View) { | |
val scrollViewHeight = height | |
val outViewPosition = IntArray(2) | |
view.getLocationOnScreen(outViewPosition) | |
val viewY = outViewPosition[1] | |
val bottom = viewY + view.height | |
val scrollToY = scrollY + (bottom - scrollViewHeight) | |
this.smoothScrollTo(0, scrollToY) | |
} | |
fun ScrollView.smoothScrollToViewTop(view: View) { | |
val outViewPosition = IntArray(2) | |
view.getLocationOnScreen(outViewPosition) | |
val viewY = outViewPosition[1] | |
val scrollToY = scrollY + viewY - view.height | |
this.smoothScrollTo(0, scrollToY) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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