16

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?

Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389

1 Answers1

16

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);
NoChinDeluxe
  • 3,446
  • 1
  • 16
  • 29
  • 3
    Thanks, but I already know how to animate a view by code :) I was just curious to find a way to do it "all-declarative" way without writing code. – Can Poyrazoğlu Apr 14 '16 at 17:33
  • I guess the question I have then, is why? What is the real question you are wanting to ask? I can't imagine writing 3 lines of code is that unreasonable for you, so there must be another reason. I can perhaps clarify for you or help you solve the real issue. – NoChinDeluxe Apr 14 '16 at 17:34
  • 3
    I didn't say that it's unreasonable. It's easy and I'm already doing it. I am just trying to move as much logic I can into declaration, rather than code behind and I was seeking for a way move animations into declaration from code. – Can Poyrazoğlu Apr 14 '16 at 17:36
  • 2
    OK well the answer is no, you must start the animation in code. – NoChinDeluxe Apr 14 '16 at 17:39
  • 1
    I see. could you please edit your answer so that it clearly states "no" in the beginning, so that I can accept it? – Can Poyrazoğlu Apr 14 '16 at 17:40