我正在尝试使用较新样式的Android属性动画器(而不是较旧的视图动画)来创建动画以水平摇动视图。
我已经在/res/animator/shake.xml
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="translationX"
android:duration="100"
android:valueFrom="0f"
android:valueTo="20f"
android:valueType="floatType"
android:interpolator="@android:anim/linear_interpolator"
android:repeatCount="7"
android:repeatMode="reverse"/>
我创建了以下Kotlin扩展方法以在任何视图上播放动画:
fun View.shake() {
AnimatorInflater.loadAnimator(context, R.animator.shake).apply {
setTarget(this)
start()
}
}
但是,当我调用动画时,什么也没有发生,而且我不确定为什么。
答案 0 :(得分:2)
请勿将setTarget(this)
和start()
放入apply{}
用以下代码替换代码:
fun View.shake() {
val al = AnimatorInflater.loadAnimator(context, R.animator.shake)
al.setTarget(this)
al.start()
}
或者您可以这样做:
AnimatorInflater.loadAnimator(context, R.animator.shake).apply {
setTarget(this@shake)
start()
}
较早的this
指的是AnimatorInflater.loadAnimator
,而不是View
,因此只需将其替换为this@shake
即可指代您所在的view
应用动画。