How to attach an animation to an object in layout XML in Android?
Asked Answered
E

1

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?

Encomium answered 14/4, 2016 at 17:23 Comment(0)
R
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);
Radiobiology answered 14/4, 2016 at 17:32 Comment(5)
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.Diarchy
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.Radiobiology
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.Diarchy
OK well the answer is no, you must start the animation in code.Radiobiology
I see. could you please edit your answer so that it clearly states "no" in the beginning, so that I can accept it?Diarchy

© 2022 - 2024 — McMap. All rights reserved.