Vlad Chernis
Aug 24, 2017 · 1 min read

Android Studio does a decent job of translating this to Kotlin, but I had to manually fix some things. Here it is:

@BindingAdapter("animatedVisibility")
@JvmStatic
fun setVisibility(view: View, visibility: Int) {
// Were we animating before? If so, what was the visibility?
val endAnimVisibility = view.getTag(R.id.finalVisibility) as Int?
val oldVisibility = endAnimVisibility ?: view.visibility

if (oldVisibility == visibility) {
// Either we're already animating to the target visibility, or we're not animating and
// are already at the target visibility. Don't start a new animation in either case.
return
}

val isVisible = oldVisibility == View.VISIBLE
val willBeVisible = visibility == View.VISIBLE

view.visibility = View.VISIBLE
val startAlpha = if (endAnimVisibility != null) {
view.alpha
} else {
if (isVisible) 1f else 0f
}
val endAlpha = if (willBeVisible) 1f else 0f

val alpha = ObjectAnimator.ofFloat(view, View.ALPHA, startAlpha, endAlpha)
alpha.setAutoCancel(true)

alpha.addListener(object : AnimatorListenerAdapter() {
private var isCanceled: Boolean = false

override fun
onAnimationStart(anim: Animator) {
view.setTag(R.id.finalVisibility, visibility)
}

override fun onAnimationCancel(anim: Animator) {
isCanceled = true
}

override fun onAnimationEnd(anim: Animator) {
view.setTag(R.id.finalVisibility, null)
if (!isCanceled) {
view.alpha = 1f
view.visibility = visibility
}
}
})
alpha.start()
}
)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade