我正在使用kotlin解构声明。我之前使用它与SpringAnimation
,它工作得很好。现在我想用它与ObjectAnimator
,我得到这个错误:
ObjectAnimator类型的解构声明初始化程序!必须有'component1()'函数
ObjectAnimator类型的解构声明初始化程序!必须有'component2()'函数
这是我的代码:
val (xanimator, alphaanim) = findViewById<View>(R.id.imageView).let { img ->
ObjectAnimator.ofFloat(img, "translationX", 100f).apply {
duration = 2000
}
to
ObjectAnimator.ofFloat(img, "alpha", 1.0f).apply {
duration = 2000
}
}
怎么了?
这里的问题是你无法在新行上启动中缀调用函数调用 - 编译器实际上是在第一次apply
调用之后推断出以分号/行结尾。这与运营商的方式相同,例如see this issue。
所以你需要重新格式化你的代码以便to
连接,最简单的是这样:
val (xanimator: ObjectAnimator, alphaanim: ObjectAnimator) = findViewById<View>(R.id.imageView).let { img ->
ObjectAnimator.ofFloat(img, "translationX", 100f).apply {
duration = 2000
} to
ObjectAnimator.ofFloat(img, "alpha", 1.0f).apply {
duration = 2000
}
}
但为了便于阅读,也许你可以选择这样的东西:
val (xanimator: ObjectAnimator, alphaanim: ObjectAnimator) = findViewById<View>(R.id.imageView).let { img ->
Pair(
ObjectAnimator.ofFloat(img, "translationX", 100f).apply {
duration = 2000
},
ObjectAnimator.ofFloat(img, "alpha", 1.0f).apply {
duration = 2000
}
)
}
或者介于两者之间。