Skip to content

Instantly share code, notes, and snippets.

@gpeal
Last active October 2, 2024 04:10
Show Gist options
  • Save gpeal/2784b455cfd22d7ba567fa9c24144656 to your computer and use it in GitHub Desktop.
Save gpeal/2784b455cfd22d7ba567fa9c24144656 to your computer and use it in GitHub Desktop.
Fade To
/**
* Fade a view to visible or gone. This function is idempotent - it can be called over and over again with the same
* value without affecting an in-progress animation.
*/
fun View.fadeTo(visible: Boolean, duration: Long = 500, startDelay: Long = 0, toAlpha: Float = 1f) {
// Make this idempotent.
val tagKey = "fadeTo".hashCode()
if (visible == isVisible && animation == null && getTag(tagKey) == null) return
if (getTag(tagKey) == visible) return
setTag(tagKey, visible)
setTag("fadeToAlpha".hashCode(), toAlpha)
if (visible && alpha == 1f) alpha = 0f
animate()
.alpha(if (visible) toAlpha else 0f)
.withStartAction {
if (visible) isVisible = true
}
.withEndAction {
setTag(tagKey, null)
if (isAttachedToWindow && !visible) isVisible = false
}
.setInterpolator(FastOutSlowInInterpolator())
.setDuration(duration)
.setStartDelay(startDelay)
.start()
}
/**
* Cancels the animation started by [fadeTo] and jumps to the end of it.
*/
fun View.cancelFade() {
val tagKey = "fadeTo".hashCode()
val visible = getTag(tagKey)?.castOrNull<Boolean>() ?: return
animate().cancel()
isVisible = visible
alpha = if (visible) getTag("fadeToAlpha".hashCode())?.castOrNull<Float>() ?: 1f else 0f
setTag(tagKey, null)
}
/**
* Cancels the fade for this view and any ancestors.
*/
fun View.cancelFadeRecursively() {
cancelFade()
castOrNull<ViewGroup>()?.children?.asSequence()?.forEach { it.cancelFade() }
}
@Suppress("UNCHECKED_CAST")
inline fun <reified T> Any?.castOrNull(): T? = this as? T
@avipars
Copy link

avipars commented May 1, 2021

does it work for java?

@gpeal
Copy link
Author

gpeal commented May 1, 2021

@avipars nothing about this couldn't be converted to Java. You could also make it @JvmStatic to turn it into a utils function like ViewUtils.fadeTo(view, true/false);
https://kotlinlang.org/docs/java-to-kotlin-interop.html#package-level-functions

@Dailius
Copy link

Dailius commented Aug 31, 2021

@gpeal could you provide castOrNull<>() function, Unresolved reference: castOrNull

@gpeal
Copy link
Author

gpeal commented Aug 31, 2021

@Dailius added

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment