效果预览
仅需几行代码(Kotlin)
inline fun TextView.startNumberDanceAnimation(number: Number, duration: Long) {
val ani = ValueAnimator.ofFloat(0f, number.toFloat()).setDuration(duration)
val format = "%1\$01.${if (number is Float) "2" else "0"}f"
ani.interpolator = AccelerateInterpolator()
ani.addUpdateListener {
text = String.format(format, it.animatedValue)
}
ani.start()
}
调用函数
val tv = findViewById<TextView>(R.id.tvNumber)
val tv2 = findViewById<TextView>(R.id.tvNumber2)
tv.startNumberDanceAnimation(3001, 900)
tv2.startNumberDanceAnimation(8060.33f, 900)
方案优势
1)一个函数即可实现,无需引入新的TextView子类;
2)代码简单易维护;