首页 > 解决方案 > 为什么这个android动画没有做任何事情?

问题描述

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

我已经编写了以下 XML 动画师/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()
    }
}

然而,当我调用动画时,什么也没有发生,我不知道为什么。

标签: androidkotlinandroid-animationandroid-xmlobjectanimator

解决方案


不要放入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您正在应用动画的 。


推荐阅读