How to attach an animation to an object in layout XML in Android?
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);
![Can Poyrazoğlu](https://i.stack.imgur.com/aVcPB.jpg?s=256&g=1)
Can Poyrazoğlu
Has most experience in iOS programming and UI design. Loves astrophotography, board sports, feeding street animals, authoring his humble blog, and flying drones.
Updated on June 14, 2022Comments
-
Can Poyrazoğlu about 2 years
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 about 8 yearsThanks, 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.
-
NoChinDeluxe about 8 yearsI 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.
-
Can Poyrazoğlu about 8 yearsI 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.
-
NoChinDeluxe about 8 yearsOK well the answer is no, you must start the animation in code.
-
Can Poyrazoğlu about 8 yearsI see. could you please edit your answer so that it clearly states "no" in the beginning, so that I can accept it?