Search code examples
androidkotlinandroid-animationandroid-xmlobjectanimator

Why isn't this android animation doing anything?


I'm trying to use the newer style of Android property animators (rather than the older view animations) to create an animation to shake a view horizontally.

I've written the following XML animator in /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"/>

I have created the following Kotlin extension method to play the animation on any view:

fun View.shake() {
    AnimatorInflater.loadAnimator(context, R.animator.shake).apply {
        setTarget(this)
        start()
    }
}

When I call the animation however, nothing happens, and I'm not sure why.


Solution

  • Don't put setTarget(this) and start() in apply{}

    Replace your code with this:

    fun View.shake() {
        val al = AnimatorInflater.loadAnimator(context, R.animator.shake)
        al.setTarget(this)
        al.start()
    }
    

    Or you can do:

    AnimatorInflater.loadAnimator(context, R.animator.shake).apply {
            setTarget(this@shake)
            start()
        }
    

    Earlier this was referring to AnimatorInflater.loadAnimator and not the View, so just replace it with this@shake to refer it to the view on which you are applying the animation.