Looking for a better way to reset Animator

11 views Asked by At

I'm working on a button bubble animation. I have it working but I'm not super happy with how to reset the animators after each press. I am trying to not re-create objects unneccessarily (it totally works if I do that, or call clone() on each animation)

The problem is that the first oscillation works when the button scale is 1.0. But I have a zoom animation when the button Is pressed, so the button scale is not always 1.0 at the start. The first time I create the object, the animator seems somehow to adapt the animation from the scale of the button, but the rest of the times, it always starts at 1.0, regardless of the buttons current scale.

So, what I have ended up doing is to calculate the progress of the scale and set the "playtime" so that it starts from the current scale.

My question is: why can't I reset the animation so that it works like it does the first time? It should be simpler than this IMO.

My code (abbreviated, touch tracking is more elaborate and :

private fun createScaleAnimator(duration: Long, scaleX: Float, scaleY: Float): ObjectAnimator {
    return ObjectAnimator.ofPropertyValuesHolder(
        this,
        PropertyValuesHolder.ofFloat("scaleX", scaleX),
        PropertyValuesHolder.ofFloat("scaleY", scaleY)
    ).apply {
        this.duration = duration
    }
}

val enlargeStep1 = createScaleAnimator(100, 0.85f, 0.85f)
val enlargeStep2 = createScaleAnimator(180, 1.05f, 1.05f)
val enlargeStep3 = createScaleAnimator(180, 0.98f, 0.98f)
val enlargeStep4 = createScaleAnimator(170, 1.01f, 1.01f)
val enlargeStep5 = createScaleAnimator(170, 1f, 1f)

val enlargeAnimator = AnimatorSet().apply {
    playSequentially(enlargeStep1, enlargeStep2, enlargeStep3, enlargeStep4, enlargeStep5)
}

private fun beginEnlargeAnimation() {
    val playTime = if (scaleX == 1.0f) 0L else (enlargeStep1.duration.toFloat() * (100 - (scaleX - 0.85) / 0.15)).toLong()
    enlargeStep1.currentPlayTime = playTime

    /*the first time this animator takes the current scale value into account, but on any subsequent animation it starts from 1.0 even if the button current seale is for example 0.95. How can I make this work like the first time without the above calc lines?*/
    enlargeAnimator.start()
}


private fun beginShrinkAnimation() {
    //shrinks the button
}

override fun onTouchEvent(event: MotionEvent): Boolean {
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            beginShrinkAnimation()
        }
        MotionEvent.ACTION_UP -> {
            beginEnlargeAnimation()
        }
        MotionEvent.ACTION_CANCEL -> {
            beginEnlargeAnimation()
        }
    }
    return super.onTouchEvent(event)
}
0

There are 0 answers