Last active
May 27, 2017 07:16
-
-
Save zsmb13/96249d5170522872bfb64320d6229e8a to your computer and use it in GitHub Desktop.
Some useful extension functions for Android development
This file contains 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
_ |
This file contains 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.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 | |
} |
This file contains 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.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