I am trying to animate 3 icons in my Activity using ObjectAnimator.
The animation itself works fine but when I test it by locking and unlocking the screen, the animation freezes/gets stuck, usually after the second time locking and unlocking the screen. Once it is stuck, locking & unlocking does not release/resume animations.
I tried to cancel and start the Animators in onPause() and onResume() respectively, but it doesn't seem to work. Also tried many other suggestions on Stack Overflow but couldn't find a proper solution to this issue.
Class responsible for animations:
class MyAnimator(views: List<View>) {
private var animators = listOf<Animator>()
init {
animators = views.map { createAnimator(it) }
}
fun startAnimations() {
animators.forEach {
it.start()
}
}
fun cancelAnimations() {
animators.forEach {
it.cancel()
}
}
private fun createAnimator(view: View): Animator {
val jumpAnimation = ObjectAnimator.ofFloat(view, "y", 40f, 360f).apply {
repeatCount = INFINITE
repeatMode = ValueAnimator.REVERSE
}
val rotateAnimation = ObjectAnimator.ofFloat(view, "rotation", 360f).apply {
repeatCount = INFINITE
repeatMode = ValueAnimator.REVERSE
}
return AnimatorSet().apply {
duration = Random.nextLong(1200, 1800)
playTogether(jumpAnimation, rotateAnimation)
}
}
}
Activity:
class MyActivity : AppCompatActivity() {
private lateinit var animator: MyAnimator
private var icons = listOf<ImageView>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_layout)
gameIcons = listOf(firstIconIV, secondIconIV, thirdIconIV)
animator = MyAnimator(gameIcons)
}
override fun onPause() {
super.onPause()
animator.cancelAnimations()
}
override fun onResume() {
super.onResume()
animator.startAnimations()
}
}