Search code examples
androidkotlinanimationobjectanimator

How to set velocity of animation in Android


I have a set of animations, I noticed that when each piece starts the speed is very fast, how can I adjust the execution speed?

I try this but the animation is too fast

val animator1 = ObjectAnimator
            .ofFloat(binding.logoAnimated,
                "translationX", 0f, -(width - point.x)).apply {
                repeatCount = 1
                repeatMode = ValueAnimator.REVERSE
            }

        val animator2 = ObjectAnimator
            .ofFloat(binding.logoAnimated,"translationX",
                0f, +(width - point.x)).apply {
                repeatCount = 1
                repeatMode = ValueAnimator.REVERSE
            }

        val animatorSet = AnimatorSet()
        animatorSet.playSequentially(animator1, animator2)
        animatorSet.start()

Solution

  • You can adjust the execution speed of your animations sing ObjectAnimator, you can set the duration property of each ObjectAnimator instance. This property determines how long the animation takes to complete in milliseconds

    val duration = 2000L // 2000 milliseconds = 2 second
    
    
    val animator1 = ObjectAnimator
        .ofFloat(binding.logoAnimated, "translationX", 0f, -(width - point.x))
        .apply {
            this.duration = duration  // Set duration for animator1
            repeatCount = 1
            repeatMode = ValueAnimator.REVERSE
        }
    
    val animator2 = ObjectAnimator
        .ofFloat(binding.logoAnimated, "translationX", 0f, +(width - point.x))
        .apply {
            this.duration = duration  // Set duration for animator2
            repeatCount = 1
            repeatMode = ValueAnimator.REVERSE
        }
    
    
    val animatorSet = AnimatorSet()
    animatorSet.playSequentially(animator1, animator2)
    animatorSet.start()