Home » Android » android – Add animation at run time

android – Add animation at run time

Posted by: admin May 14, 2020 Leave a comment


I want to animate my AnimatedVectorDrawable at runtime without using .xml files. Actually I’m using .xml files same way as documentation’s samples shows:


So, I have vector_drawable.xml contains<vector> with nested <group> and <path> which defines a shape.

For this vector I have animated_vector_drawable.xml contains <animated-vector> with android:animation assinged to <target>.

Last step is define an animation file rotation.xml using <objectAnimator> which is used by animated_vector_drawable.xml

Everything works fine, but the problem appears, when I need to create many different shapes (vectors) with many different or similar animations, because this generate many .xml files.

  1. I can’t include ready and prepared <vector> from one .xml file to another (some kind of <include> tag) so i need to copy the same code to another files. It is very annoying.

  2. If I want to use the same animation for few <target> elements but each animation must have f.e. different delay or any property value (alpha, rotation, interpolator…) , I must create new .xml file contains <objectAnimator> with changed one property value instead of use the same, one file with changed property value. It’s also annoying.

  3. I discovered that I can use ObjectAnimator and set alpha & fillColor for AnimatedVectorDrawable but there is a problem when I want to change it’s translateX, translateY, rotation or any other properties. Is there a way to do this without .xml. I just want to have access to <group>

How to&Answers:

Constructor that you used creates animation with absolute values (pixels).

TranslateAnimation in = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 1.0f,
Animation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f, 0, 0.0f);

Try use Animation.RELATIVE_TO_PARENT to fit your needs.