Skip to content

Instantly share code, notes, and snippets.

@zsmb13
Last active May 27, 2017 07:16
Show Gist options
  • Save zsmb13/96249d5170522872bfb64320d6229e8a to your computer and use it in GitHub Desktop.
Save zsmb13/96249d5170522872bfb64320d6229e8a to your computer and use it in GitHub Desktop.
Some useful extension functions for Android development
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.TextView
/* Adds a [clickHandler] to the text starting at index [start] and ending at index [end] */
fun TextView.onClickSpan(start: Int, end: Int, clickHandler: () -> Unit) {
movementMethod = LinkMovementMethod.getInstance()
linksClickable = true
val span = object : ClickableSpan() {
override fun onClick(widget: View?) {
clickHandler()
}
}
val spannable = SpannableString(text)
spannable.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spannable
}
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.view.View
fun View.show() {
this.visibility = View.VISIBLE
}
fun View.hide() {
this.visibility = View.GONE
}
fun View.isVisible() = this.visibility == View.VISIBLE
fun View.enable() {
isEnabled = true
}
fun View.disable() {
isEnabled = false
}
/* Fades the View out in [durationMs] time */
fun <T : View> T.animateOut(durationMs: Long = 250, onComplete: T.() -> Unit = {}) {
animate().setDuration(durationMs)
.alpha(0f)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
hide()
alpha = 1f
onComplete()
}
})
}
/* Fades the View in in [durationMs] time */
fun <T : View> T.animateIn(durationMs: Long = 250, onComplete: T.() -> Unit = {}) {
alpha = 0f
show()
animate().setDuration(durationMs)
.alpha(1f)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
onComplete()
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment