Created
July 7, 2019 14:09
-
-
Save fornewid/c07f530b08964852fb788101253067b1 to your computer and use it in GitHub Desktop.
View.spring() in #io19 motional intelligence session
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
fun animateVisibility(view: View, visible: Boolean) { | |
val targetAlpha = if (visible) 1f else 0f | |
if (view.alpha == targetAlpha) return | |
view.visibility = View.VISIBLE | |
val spring = view.spring(SpringAnimation.ALPHA) | |
(view.getTag(R.id.tag_pending_end_listener) as? DynamicAnimation.OnAnimationEndListener)?.let { | |
spring.removeEndListener(it) | |
} | |
if (!visible) { | |
val listener = { | |
override fun onAnimationEnd() { | |
spring.removeEndListener(this) | |
view.visibility = View.GONE | |
} | |
} | |
spring.addEndListener(listener) | |
view.setTag(R.id.tag_pending_end_listener, listener) | |
} | |
spring.animateToFinalPosition(targetAlpha) | |
} | |
fun View.spring( | |
property: ViewProperty, | |
damping: Float = SpringForce.DAMPING_RATIO_NO_BOUNCY, | |
stiffness: Float = 500f | |
): SpringAnimation { | |
val key = getKey(property) | |
var springAnim = getTag(key) as? SpringAnimation? | |
if (springAnim == null) { | |
springAnim = SpringAnimation(this, property).apply { | |
spring = SpringForce().apply { | |
this.dampingRatio = damping | |
this.stiffness = stiffness | |
} | |
setTag(key, springAnim) | |
} | |
} | |
return springAnim | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment