为什么这个android动画不做任何事情?

时间:2018-09-21 17:29:18

标签: android kotlin android-animation android-xml objectanimator

我正在尝试使用较新样式的Android属性动画器(而不是较旧的视图动画)来创建动画以水平摇动视图。

我已经在/res/animator/shake.xml

中编写了以下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()
    }
}

但是,当我调用动画时,什么也没有发生,而且我不确定为什么。

1 个答案:

答案 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应用动画。