Search code examples
androidxmlanimationandroid-4.0-ice-cream-sandwich

How to attach an animation to an object in layout XML in Android?


I've got an animation defined in an XML resource, and I want to attach that animation to a view. I know how to perform this in code manually, but I was wondering if it's possible to attach that animation to a view directly in layout declaration. Something like:

<ImageView android:animation="@anim/my_anim" />

So that animation will autoplay without any external code invocation. Is this possible with the built-in Android SDK (I'm not looking for some external library that can add this as a drop-in functionality)? If yes, how?


Solution

  • The answer is no. You must attach the animation at runtime. But it's quite easy to do and should only take a few lines of code. For example, from the Android docs:

    ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage);
    Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);
    spaceshipImage.startAnimation(hyperspaceJumpAnimation);