3 Ways to Animate Translation of View

Hitesh Sahu
1 min readSep 15, 2021

--

Sharing a class for showcasing the ways one can animate Translation of View

class AnimationCreator {

private val defaultAnimationInterpolator: Interpolator = EaseOutExpInterpolator()

fun translateView(viewToAnimate: View, finalState: ViewBound) {

// Animate View directly
viewToAnimate.animate()
.x(finalState.positionX)
.setDuration(600L)
.setInterpolator(defaultAnimationInterpolator)
.start()

// Object Animator
ObjectAnimator.ofFloat(
viewToAnimate,
View.X,
finalState.positionX
).apply {
duration = 600
interpolator = defaultAnimationInterpolator
}.start()


// Value Animator
ValueAnimator.ofFloat(viewToAnimate.x, finalState.positionX).apply {
duration = 2000
interpolator = defaultAnimationInterpolator
addUpdateListener {
viewToAnimate.x = it.animatedValue as Float
}
start()
}
}

fun resizeView(viewToAnimate: View, finalState: ViewBound) {
ValueAnimator.ofInt(viewToAnimate.width, finalState.size.width).apply {
duration = 2000L
startDelay = 0
interpolator = defaultAnimationInterpolator
addUpdateListener {
val animatedValue = it.animatedValue as Int
val layoutParams = viewToAnimate.layoutParams
layoutParams.width = animatedValue
viewToAnimate.layoutParams = layoutParams
}
start()
}
}


private fun animateWidthTo(view: View, width: Int) {
val currentWidth = view.width
val animator = ObjectAnimator.ofInt(view, WidthProperty(), currentWidth, width)
animator.duration = 1000
animator.interpolator = DecelerateInterpolator()
animator.start()
}

class EaseOutExpInterpolator : Interpolator {
override fun getInterpolation(x: Float): Float {
return if (x == 1f) 1f else (1 - Math.pow(2.0, -10 * x.toDouble())).toFloat()
}
}

internal class WidthProperty :
Property<View, Int>(Int::class.java, "width") {
override fun get(view: View): Int {
return view.height
}

override fun set(view: View, value: Int) {
view.layoutParams.width = value
view.layoutParams = view.layoutParams
}
}

}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response