Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Last active Oct 1, 2022
Embed
What would you like to do?
@UiThread
fun View.fadeIn(
duration: Long = 250,
fromAlpha: Float? = null,
onAnimation: AlphaAnimation.() -> Unit = {},
) {
clearAnimation()
val oldAlpha = alpha
alpha = 1f
startAnimation(AlphaAnimation(fromAlpha ?: oldAlpha, 1f).apply {
this.duration = duration
onAnimation()
})
}
@UiThread
fun View.fadeOut(
duration: Long = 250,
onAnimation: AlphaAnimation.() -> Unit = {},
) {
clearAnimation()
startAnimation(AlphaAnimation(alpha, 0.0f).apply {
this.duration = duration
onAnimation()
})
}
@UiThread
fun View.tryFadeIn(
duration: Long = 250,
fromAlpha: Float? = null,
onAnimation: AlphaAnimation.() -> Unit = {},
) {
tryVisible()
return fadeIn(duration, fromAlpha) {
onAnimation()
}
}
@UiThread
fun View.tryFadeOut(
duration: Long = 250,
onAnimation: AlphaAnimation.() -> Unit = {},
) = takeIf { isVisible }?.fadeOut(duration) {
setAnimationListener { onEnd { tryInvisible() } }
onAnimation()
}
class SimpleAnimationListener(
var onRepeat: (animation: Animation?) -> Unit = {},
var onStart: (animation: Animation?) -> Unit = {},
var onEnd: (animation: Animation?) -> Unit = {},
) : Animation.AnimationListener {
fun onRepeat(action: (animation: Animation?) -> Unit) {
onRepeat = action
}
fun onStart(action: (animation: Animation?) -> Unit) {
onStart = action
}
fun onEnd(action: (animation: Animation?) -> Unit) {
onEnd = action
}
override fun onAnimationRepeat(animation: Animation?) {
onRepeat.invoke(animation)
}
override fun onAnimationStart(animation: Animation?) {
onStart.invoke(animation)
}
override fun onAnimationEnd(animation: Animation?) {
onEnd.invoke(animation)
}
}
fun Animation.setAnimationListener(
onSetListener: SimpleAnimationListener.() -> Unit = {},
) = setAnimationListener(SimpleAnimationListener().apply { onSetListener() })
@UiThread
fun <T: View> T.slideY(
to: Float = 0f,
duration: Long = animationSmallDuration,
interpolator: Interpolator? = null,
onAnimation: ValueAnimator.(T) -> Unit = {},
) = animate(
from = translationY,
to = to,
duration = duration,
interpolator = interpolator ?: FastOutSlowInInterpolator(),
onAnimation = onAnimation,
) { translationY = it }
@UiThread
fun <V: View> V.animate(
from: Float,
to: Float,
duration: Long = animationDuration,
interpolator: Interpolator? = null,
onAnimation: ValueAnimator.(V) -> Unit = {},
onUpdate: ValueAnimator.(Float) -> Unit = {},
) {
if (from != to) {
clearAnimation()
val view = this
ValueAnimator.ofFloat(from, to).apply {
this.duration = duration
interpolator?.let { this.interpolator = it }
onAnimation(view)
addUpdateListener { (it.animatedValue as? Float)?.let { value ->
it.onUpdate(value)
} }
}.start()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment