Why do all the android animator methods work only the first time? Then only the last method works

Issue

Why does my button only rotate on the first click after the activity is created? On the second and subsequent pressing of the button, the button only rises up and down along the Y axis.

findViewById<Button>(R.id.clearChkBtn).setOnClickListener {
        val x = it.x
        val y = it.y
        it.animate().setDuration(3000).alpha(0.1f).rotation(540f).x(50f).y(50f).setListener(object : Animator.AnimatorListener{
                override fun onAnimationEnd(animation: Animator?) {
                       it.animate().setDuration(3000).alpha(1f).rotation(0f).x(x).y(y)
                }
                override fun onAnimationStart(animation: Animator?) = Unit
                override fun onAnimationCancel(animation: Animator?) = Unit
                override fun onAnimationRepeat(animation: Animator?) = Unit
        })
}

What it looks like:
https://www.youtube.com/watch?v=2ovJAdZwNpw

Solution

I tried your code and same happened for me, however the issue is that you need to clear the animation in order to perform it again, using

it.clearAnimation

but since you are applying again an animation to get it back, you need to add listener to new animation and clear it there this way

 it.animate().setDuration(3000).alpha(0.1f).rotation(359f).x(50f).y(50f).setListener(object : Animator.AnimatorListener{
            override fun onAnimationEnd(animation: Animator?) {
                it.animate().setDuration(3000).alpha(1f).rotation(0f).x(x).y(y).setListener(object : Animator.AnimatorListener{
                    override fun onAnimationStart(p0: Animator?) {

                    }

                    override fun onAnimationEnd(p0: Animator?) {
                        it.clearAnimation()
                    }

                    override fun onAnimationCancel(p0: Animator?) {
                    }

                    override fun onAnimationRepeat(p0: Animator?) {
                    }

                })

            }
            override fun onAnimationStart(animation: Animator?) = Unit
            override fun onAnimationCancel(animation: Animator?) = Unit
            override fun onAnimationRepeat(animation: Animator?) = Unit
        })
    }

Answered By – Haider Saleem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published