如何控制ValueAnimator的更新速度

How to control the update speed of ValueAnimator

10秒内,从1到10

正常计算结果为

1,
1.1,
1.2,
1.3
...
9.7,
9.8,
9.9,
10

我想要的结果是

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

每秒更新

如何实现?

谢谢 ------------------例子------------------------

        ValueAnimator.setFrameDelay(1000)
        val animator = ValueAnimator.ofInt(1, 5)
        animator.addUpdateListener { animation ->
            Log.d("TTT", "${animation.animatedValue}")
        }
        animator.duration = 5000
        animator.start()

日志:

2020-10-14 03:40:18.883 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:18.900 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:18.916 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:18.933 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:19.131 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:19.147 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:19.478 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:19.494 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:20.073 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:20.089 28503-28503/XXXXX D/TTT: 2
2020-10-14 03:40:20.319 28503-28503/XXXXX D/TTT: 2
2020-10-14 03:40:20.336 28503-28503/XXXXX D/TTT: 2
2020-10-14 03:40:20.469 28503-28503/XXXXX D/TTT: 2
2020-10-14 03:40:20.485 28503-28503/XXXXX D/TTT: 2
2020-10-14 03:40:20.584 28503-28503/XXXXX D/TTT: 2
2020-10-14 03:40:20.600 28503-28503/XXXXX D/TTT: 2
2020-10-14 03:40:20.914 28503-28503/XXXXX D/TTT: 2
2020-10-14 03:40:20.931 28503-28503/XXXXX D/TTT: 3
2020-10-14 03:40:21.475 28503-28503/XXXXX D/TTT: 3
2020-10-14 03:40:21.491 28503-28503/XXXXX D/TTT: 3
2020-10-14 03:40:21.756 28503-28503/XXXXX D/TTT: 3
2020-10-14 03:40:21.772 28503-28503/XXXXX D/TTT: 4
2020-10-14 03:40:22.465 28503-28503/XXXXX D/TTT: 4
2020-10-14 03:40:22.481 28503-28503/XXXXX D/TTT: 4
2020-10-14 03:40:23.406 28503-28503/XXXXX D/TTT: 4
2020-10-14 03:40:23.422 28503-28503/XXXXX D/TTT: 5

我需要这样的:

2020-10-14 03:40:21.772 28503-28503/XXXXX D/TTT: 1
2020-10-14 03:40:22.465 28503-28503/XXXXX D/TTT: 2
2020-10-14 03:40:22.481 28503-28503/XXXXX D/TTT: 3
2020-10-14 03:40:23.406 28503-28503/XXXXX D/TTT: 4
2020-10-14 03:40:23.422 28503-28503/XXXXX D/TTT: 5

无法调整 ValueAniamtor 更新率,因为它用于动画,因此会以非常高的速度刷新。

相反,您可以使用 Timer class,按特定速率进行调度,例如下一个:

Timer().scheduleAtFixedRate(object : TimerTask() {
        var value = 1 // Initial value

        override fun run() {
            value++

            Log.d("TTT", "$value")

            if (value > 10)  // Exit after 10
                this.cancel()
        }
    }, 0, 500) // Update every 500 milliseconds

例如,如果您需要 5 秒持续时间的 10 次迭代,则将更新速率设置为 500,(公式:5000 毫秒 / 10 次迭代)

您可以使用 CountDownTimer:

val timer = object : CountDownTimer(5000L, 1000L) {
    var counter = 1
    override fun onTick(millisUntilFinished: Long) {
        Log.d("TTT", "${counter++}")
    }

    override fun onFinish() {}
}

timer.start()