我想扩展 ValueAnimator 类来覆盖一些方法
class ColorAnimator : ValueAnimator() {
override fun start() {
/* ------ */
super.start()
}
override fun end() {
/* ------ */
super.end()
}
}
然后我实例化我的新类
val mAnimator = (ValueAnimator.ofArgb(color1, color2) as ColorAnimator).apply {
addUpdateListener { btn.background.setTint(it.animatedValue as Int) }
duration = 1000
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.REVERSE
}
mAnimator.start()
但是我得到这个错误
java.lang.ClassCastException: android.animation.ValueAnimator 无法转换为 ColorAnimator
ValueAnimator.ofArgb
返回一个 ValueAnimator,ColorAnimator 是它的继承者。我做错了什么?
ValueAnimator.ofArgb
不会实例化您的新类,它总是创建一个 ValueAnimator
对象,因此您不能将其转换为它的 subclass ColorAnimator
。这是因为定义一个新的(子)类不会自动改变其他方法的行为。
最简单的解决方案是向
ColorAnimator
添加另一个静态方法来执行您想要的操作:
class ColorAnimator : ValueAnimator() {
companion object {
@JvmStatic // if you want to use it from Java
fun ofArgb(vararg values: Int): ColorAnimator {
return ValueAnimator().apply {
setIntValues(*values)
// ValueAnimator uses static instance of ArgbEvaluator
// that cannot be accessed from app's code.
// You might want to store your own instance
// to avoid extra memory allocations.
setEvaluator(ArgbEvaluator())
}
}
}
}