我想使用自定义属性为自定义 View 位置设置动画,如下所示:
class ProgressFab : ImageView {
// constructors ... etc
val path = Path()
init {
path.moveTo(0f, 0f)
path.lineTo(700f, 500f)
}
@SuppressWarnings("unused")
public fun setFubPosition(path: FloatArray) {
this.x = path[0]
this.y = path[1]
}
fun startMotion() {
val animator = ObjectAnimator.ofMultiFloat(this, "fubPosition", path)
animator.duration = 5000
animator.addUpdateListener {
//(1) this.x = (it?.animatedValue as FloatArray)[0]
//(2) this.y = (it?.animatedValue as FloatArray)[1]
invalidate()
}
animator.start()
}
}
在调用 startMotion()
后,动画器启动但 setFubPosition(path: FloatArray)
未调用。如果我取消注释 (1) 和 (2) 一切正常。
这是反编译的 kotlin 字节码(一切看起来都很好):
public final void setFubPosition(@NotNull float[] path) {
Intrinsics.checkParameterIsNotNull(path, "path");
this.setX(path[0]);
this.setY(path[1]);
}
如果我尝试使用 ofFloat
方法为自定义属性设置动画,则属性 setter 可以正常工作:
val animator = ObjectAnimator.ofFloat(this, "fubPosition", 0f, 100f);
在 kotlin 中是否可以使用 ofMultiFloat
或 ofMultiInt
方法通过属性 setter 自动更改属性?
最佳答案
来自 ObjectAnimator.ofMultiFloat()
的文档你得到
In this variation, the coordinates are float x and y coordinates used in the first and second parameter of the setter, respectively.
因此不支持数组作为属性的参数,但支持多个参数。只需更改 setter 的签名即可反射(reflect)此要求:
@SuppressWarnings("unused")
public fun setFubPosition(x: Float, y: Float) {
this.x = x
this.y = y
}
关于android - 具有自定义属性的 ObjectAnimator 不调用属性 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51112497/