1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.systemui.shared.clocks 18 19 import android.animation.Animator 20 import android.animation.AnimatorListenerAdapter 21 import android.animation.TimeInterpolator 22 import android.animation.ValueAnimator 23 import com.android.systemui.plugins.clocks.VPointF 24 import com.android.systemui.plugins.clocks.VPointF.Companion.times 25 26 class DigitTranslateAnimator(private val updateCallback: (VPointF) -> Unit) { 27 var currentTranslation = VPointF.ZERO 28 var baseTranslation = VPointF.ZERO 29 var targetTranslation = VPointF.ZERO 30 31 private val bounceAnimator: ValueAnimator = <lambda>null32 ValueAnimator.ofFloat(1f).apply { 33 addUpdateListener { updateCallback(getInterpolatedTranslation(it.animatedFraction)) } 34 addListener( 35 object : AnimatorListenerAdapter() { 36 override fun onAnimationEnd(animation: Animator) { 37 baseTranslation = currentTranslation 38 } 39 40 override fun onAnimationCancel(animation: Animator) { 41 baseTranslation = currentTranslation 42 } 43 } 44 ) 45 } 46 animatePositionnull47 fun animatePosition( 48 animate: Boolean = true, 49 delay: Long = 0, 50 duration: Long, 51 interpolator: TimeInterpolator? = null, 52 targetTranslation: VPointF, 53 onAnimationEnd: Runnable? = null, 54 ) { 55 this.targetTranslation = targetTranslation 56 if (animate) { 57 bounceAnimator.cancel() 58 bounceAnimator.startDelay = delay 59 bounceAnimator.duration = duration 60 interpolator?.let { bounceAnimator.interpolator = it } 61 if (onAnimationEnd != null) { 62 val listener = 63 object : AnimatorListenerAdapter() { 64 override fun onAnimationEnd(animation: Animator) { 65 onAnimationEnd.run() 66 bounceAnimator.removeListener(this) 67 } 68 69 override fun onAnimationCancel(animation: Animator) { 70 bounceAnimator.removeListener(this) 71 } 72 } 73 bounceAnimator.addListener(listener) 74 } 75 bounceAnimator.start() 76 } else { 77 // No animation is requested, thus set base and target state to the same state. 78 currentTranslation = targetTranslation 79 baseTranslation = targetTranslation 80 updateCallback(targetTranslation) 81 } 82 } 83 getInterpolatedTranslationnull84 fun getInterpolatedTranslation(progress: Float): VPointF { 85 return baseTranslation + progress * (targetTranslation - baseTranslation) 86 } 87 } 88