Luis
Luis

Reputation: 61

How to loop an animation of a button in Kotlin?

I would like to know how to loop the following animation of a button in Kotlin:

Example: https://ibb.co/XD7H073

As you can see in the image my goal is to constantly move the button up and down.

Here are the core parts of the code I´m trying to write:

ObjectAnimator.ofFloat(button, "translationY", 30f).apply {
                duration = 500
                start()
            }
ObjectAnimator.ofFloat(button, "translationY", -30f).apply {
                duration = 500
                start()
            }

Thanks to the one who can show me how to put these two animations in an array and then loop the array infinitely!

////////////////// Solution:

val animations = arrayOf(-140f).map { translation ->
        ObjectAnimator.ofFloat(button, "translationX", translation).apply {
            duration = 800
            repeatCount = ObjectAnimator.INFINITE
            repeatMode = ObjectAnimator.RESTART
        }
    }

Upvotes: 1

Views: 1516

Answers (1)

Stanislaw Baranski
Stanislaw Baranski

Reputation: 1418

Not tested, you may need to play with ObjectAnimator.REVERSE/RESTART and/or add from value in ObjectAnimator.ofFloat(_, _, from, to)

val animations = arrayOf(30f, -30f).map { translation ->
    ObjectAnimator.ofFloat(button, "translationY", translation).apply {
        duration = 500
        repeatCount = ObjectAnimator.INFINITE
        repeatMode = ObjectAnimator.REVERSE
    }
}

val set = AnimatorSet()
set.playTogether(animations)
set.start()

Upvotes: 2

Related Questions