AnimatedVectorDrawable.java revision 6f6578e81c1df207da47e2e1337382341f271206
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
12 * the License.
13 */
14
15package android.graphics.drawable;
16
17import android.animation.Animator;
18import android.animation.AnimatorInflater;
19import android.animation.ValueAnimator;
20import android.annotation.NonNull;
21import android.content.res.ColorStateList;
22import android.content.res.Resources;
23import android.content.res.Resources.Theme;
24import android.content.res.TypedArray;
25import android.graphics.Canvas;
26import android.graphics.ColorFilter;
27import android.graphics.Outline;
28import android.graphics.PorterDuff;
29import android.graphics.Rect;
30import android.util.ArrayMap;
31import android.util.AttributeSet;
32import android.util.Log;
33
34import com.android.internal.R;
35
36import org.xmlpull.v1.XmlPullParser;
37import org.xmlpull.v1.XmlPullParserException;
38
39import java.io.IOException;
40import java.util.ArrayList;
41
42/**
43 * This class uses {@link android.animation.ObjectAnimator} and
44 * {@link android.animation.AnimatorSet} to animate the properties of a
45 * {@link android.graphics.drawable.VectorDrawable} to create an animated drawable.
46 * <p>
47 * AnimatedVectorDrawable are normally defined as 3 separate XML files.
48 * </p>
49 * <p>
50 * First is the XML file for {@link android.graphics.drawable.VectorDrawable}.
51 * Note that we allow the animation happen on the group's attributes and path's
52 * attributes, which requires they are uniquely named in this xml file. Groups
53 * and paths without animations do not need names.
54 * </p>
55 * <li>Here is a simple VectorDrawable in this vectordrawable.xml file.
56 * <pre>
57 * &lt;vector xmlns:android=&quot;http://schemas.android.com/apk/res/android";
58 *     android:height=&quot;64dp&quot;
59 *     android:width=&quot;64dp&quot;
60 *     android:viewportHeight=&quot;600&quot;
61 *     android:viewportWidth=&quot;600&quot; &gt;
62 *     &lt;group
63 *         android:name=&quot;rotationGroup&quot;
64 *         android:pivotX=&quot;300.0&quot;
65 *         android:pivotY=&quot;300.0&quot;
66 *         android:rotation=&quot;45.0&quot; &gt;
67 *         &lt;path
68 *             android:name=&quot;v&quot;
69 *             android:fillColor=&quot;#000000&quot;
70 *             android:pathData=&quot;M300,70 l 0,-70 70,70 0,0 -70,70z&quot; /&gt;
71 *     &lt;/group&gt;
72 * &lt;/vector&gt;
73 * </pre></li>
74 * <p>
75 * Second is the AnimatedVectorDrawable's xml file, which defines the target
76 * VectorDrawable, the target paths and groups to animate, the properties of the
77 * path and group to animate and the animations defined as the ObjectAnimators
78 * or AnimatorSets.
79 * </p>
80 * <li>Here is a simple AnimatedVectorDrawable defined in this avd.xml file.
81 * Note how we use the names to refer to the groups and paths in the vectordrawable.xml.
82 * <pre>
83 * &lt;animated-vector xmlns:android=&quot;http://schemas.android.com/apk/res/android";
84 *   android:drawable=&quot;@drawable/vectordrawable&quot; &gt;
85 *     &lt;target
86 *         android:name=&quot;rotationGroup&quot;
87 *         android:animation=&quot;@anim/rotation&quot; /&gt;
88 *     &lt;target
89 *         android:name=&quot;v&quot;
90 *         android:animation=&quot;@anim/path_morph&quot; /&gt;
91 * &lt;/animated-vector&gt;
92 * </pre></li>
93 * <p>
94 * Last is the Animator xml file, which is the same as a normal ObjectAnimator
95 * or AnimatorSet.
96 * To complete this example, here are the 2 animator files used in avd.xml:
97 * rotation.xml and path_morph.xml.
98 * </p>
99 * <li>Here is the rotation.xml, which will rotate the target group for 360 degrees.
100 * <pre>
101 * &lt;objectAnimator
102 *     android:duration=&quot;6000&quot;
103 *     android:propertyName=&quot;rotation&quot;
104 *     android:valueFrom=&quot;0&quot;
105 *     android:valueTo=&quot;360&quot; /&gt;
106 * </pre></li>
107 * <li>Here is the path_morph.xml, which will morph the path from one shape to
108 * the other. Note that the paths must be compatible for morphing.
109 * In more details, the paths should have exact same length of commands , and
110 * exact same length of parameters for each commands.
111 * Note that the path string are better stored in strings.xml for reusing.
112 * <pre>
113 * &lt;set xmlns:android=&quot;http://schemas.android.com/apk/res/android">;
114 *     &lt;objectAnimator
115 *         android:duration=&quot;3000&quot;
116 *         android:propertyName=&quot;pathData&quot;
117 *         android:valueFrom=&quot;M300,70 l 0,-70 70,70 0,0   -70,70z&quot;
118 *         android:valueTo=&quot;M300,70 l 0,-70 70,0  0,140 -70,0 z&quot;
119 *         android:valueType=&quot;pathType&quot;/&gt;
120 * &lt;/set&gt;
121 * </pre></li>
122 *
123 * @attr ref android.R.styleable#AnimatedVectorDrawable_drawable
124 * @attr ref android.R.styleable#AnimatedVectorDrawableTarget_name
125 * @attr ref android.R.styleable#AnimatedVectorDrawableTarget_animation
126 */
127public class AnimatedVectorDrawable extends Drawable implements Animatable {
128    private static final String LOGTAG = AnimatedVectorDrawable.class.getSimpleName();
129
130    private static final String ANIMATED_VECTOR = "animated-vector";
131    private static final String TARGET = "target";
132
133    private static final boolean DBG_ANIMATION_VECTOR_DRAWABLE = false;
134
135    private AnimatedVectorDrawableState mAnimatedVectorState;
136
137    private boolean mMutated;
138
139    public AnimatedVectorDrawable() {
140        mAnimatedVectorState = new AnimatedVectorDrawableState(
141                new AnimatedVectorDrawableState(null));
142    }
143
144    private AnimatedVectorDrawable(AnimatedVectorDrawableState state, Resources res,
145            Theme theme) {
146        mAnimatedVectorState = new AnimatedVectorDrawableState(state);
147        if (theme != null && canApplyTheme()) {
148            applyTheme(theme);
149        }
150    }
151
152    @Override
153    public Drawable mutate() {
154        if (!mMutated && super.mutate() == this) {
155            mAnimatedVectorState = new AnimatedVectorDrawableState(mAnimatedVectorState);
156            mMutated = true;
157        }
158        return this;
159    }
160
161    @Override
162    public ConstantState getConstantState() {
163        return mAnimatedVectorState;
164    }
165
166    @Override
167    public void draw(Canvas canvas) {
168        mAnimatedVectorState.mVectorDrawable.draw(canvas);
169        if (isStarted()) {
170            invalidateSelf();
171        }
172    }
173
174    @Override
175    protected void onBoundsChange(Rect bounds) {
176        mAnimatedVectorState.mVectorDrawable.setBounds(bounds);
177    }
178
179    @Override
180    protected boolean onStateChange(int[] state) {
181        return mAnimatedVectorState.mVectorDrawable.setState(state);
182    }
183
184    @Override
185    protected boolean onLevelChange(int level) {
186        return mAnimatedVectorState.mVectorDrawable.setLevel(level);
187    }
188
189    @Override
190    public int getAlpha() {
191        return mAnimatedVectorState.mVectorDrawable.getAlpha();
192    }
193
194    @Override
195    public void setAlpha(int alpha) {
196        mAnimatedVectorState.mVectorDrawable.setAlpha(alpha);
197    }
198
199    @Override
200    public void setColorFilter(ColorFilter colorFilter) {
201        mAnimatedVectorState.mVectorDrawable.setColorFilter(colorFilter);
202    }
203
204    @Override
205    public void setTintList(ColorStateList tint) {
206        mAnimatedVectorState.mVectorDrawable.setTintList(tint);
207    }
208
209    @Override
210    public void setHotspot(float x, float y) {
211        mAnimatedVectorState.mVectorDrawable.setHotspot(x, y);
212    }
213
214    @Override
215    public void setHotspotBounds(int left, int top, int right, int bottom) {
216        mAnimatedVectorState.mVectorDrawable.setHotspotBounds(left, top, right, bottom);
217    }
218
219    @Override
220    public void setTintMode(PorterDuff.Mode tintMode) {
221        mAnimatedVectorState.mVectorDrawable.setTintMode(tintMode);
222    }
223
224    @Override
225    public boolean setVisible(boolean visible, boolean restart) {
226        mAnimatedVectorState.mVectorDrawable.setVisible(visible, restart);
227        return super.setVisible(visible, restart);
228    }
229
230    /** {@hide} */
231    @Override
232    public void setLayoutDirection(int layoutDirection) {
233        mAnimatedVectorState.mVectorDrawable.setLayoutDirection(layoutDirection);
234    }
235
236    @Override
237    public boolean isStateful() {
238        return mAnimatedVectorState.mVectorDrawable.isStateful();
239    }
240
241    @Override
242    public int getOpacity() {
243        return mAnimatedVectorState.mVectorDrawable.getOpacity();
244    }
245
246    @Override
247    public int getIntrinsicWidth() {
248        return mAnimatedVectorState.mVectorDrawable.getIntrinsicWidth();
249    }
250
251    @Override
252    public int getIntrinsicHeight() {
253        return mAnimatedVectorState.mVectorDrawable.getIntrinsicHeight();
254    }
255
256    @Override
257    public void getOutline(@NonNull Outline outline) {
258        mAnimatedVectorState.mVectorDrawable.getOutline(outline);
259    }
260
261    @Override
262    public void inflate(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme)
263            throws XmlPullParserException, IOException {
264
265        int eventType = parser.getEventType();
266        float pathErrorScale = 1;
267        while (eventType != XmlPullParser.END_DOCUMENT) {
268            if (eventType == XmlPullParser.START_TAG) {
269                final String tagName = parser.getName();
270                if (ANIMATED_VECTOR.equals(tagName)) {
271                    final TypedArray a = obtainAttributes(res, theme, attrs,
272                            R.styleable.AnimatedVectorDrawable);
273                    int drawableRes = a.getResourceId(
274                            R.styleable.AnimatedVectorDrawable_drawable, 0);
275                    if (drawableRes != 0) {
276                        VectorDrawable vectorDrawable = (VectorDrawable) res.getDrawable(
277                                drawableRes, theme).mutate();
278                        vectorDrawable.setAllowCaching(false);
279                        pathErrorScale = vectorDrawable.getPixelSize();
280                        mAnimatedVectorState.mVectorDrawable = vectorDrawable;
281                    }
282                    a.recycle();
283                } else if (TARGET.equals(tagName)) {
284                    final TypedArray a = obtainAttributes(res, theme, attrs,
285                            R.styleable.AnimatedVectorDrawableTarget);
286                    final String target = a.getString(
287                            R.styleable.AnimatedVectorDrawableTarget_name);
288
289                    int id = a.getResourceId(
290                            R.styleable.AnimatedVectorDrawableTarget_animation, 0);
291                    if (id != 0) {
292                        Animator objectAnimator = AnimatorInflater.loadAnimator(res, theme, id,
293                                pathErrorScale);
294                        setupAnimatorsForTarget(target, objectAnimator);
295                    }
296                    a.recycle();
297                }
298            }
299
300            eventType = parser.next();
301        }
302    }
303
304    @Override
305    public boolean canApplyTheme() {
306        return super.canApplyTheme() || mAnimatedVectorState != null
307                && mAnimatedVectorState.mVectorDrawable != null
308                && mAnimatedVectorState.mVectorDrawable.canApplyTheme();
309    }
310
311    @Override
312    public void applyTheme(Theme t) {
313        super.applyTheme(t);
314
315        final VectorDrawable vectorDrawable = mAnimatedVectorState.mVectorDrawable;
316        if (vectorDrawable != null && vectorDrawable.canApplyTheme()) {
317            vectorDrawable.applyTheme(t);
318        }
319    }
320
321    private static class AnimatedVectorDrawableState extends ConstantState {
322        int mChangingConfigurations;
323        VectorDrawable mVectorDrawable;
324        ArrayList<Animator> mAnimators;
325        ArrayMap<Animator, String> mTargetNameMap;
326
327        public AnimatedVectorDrawableState(AnimatedVectorDrawableState copy) {
328            if (copy != null) {
329                mChangingConfigurations = copy.mChangingConfigurations;
330                if (copy.mVectorDrawable != null) {
331                    mVectorDrawable = (VectorDrawable) copy.mVectorDrawable.getConstantState().newDrawable();
332                    mVectorDrawable.mutate();
333                    mVectorDrawable.setAllowCaching(false);
334                    mVectorDrawable.setBounds(copy.mVectorDrawable.getBounds());
335                }
336                if (copy.mAnimators != null) {
337                    final int numAnimators = copy.mAnimators.size();
338                    mAnimators = new ArrayList<Animator>(numAnimators);
339                    mTargetNameMap = new ArrayMap<Animator, String>(numAnimators);
340                    for (int i = 0; i < numAnimators; ++i) {
341                        Animator anim = copy.mAnimators.get(i);
342                        Animator animClone = anim.clone();
343                        String targetName = copy.mTargetNameMap.get(anim);
344                        Object targetObject = mVectorDrawable.getTargetByName(targetName);
345                        animClone.setTarget(targetObject);
346                        mAnimators.add(animClone);
347                        mTargetNameMap.put(animClone, targetName);
348                    }
349                }
350            }
351        }
352
353        @Override
354        public Drawable newDrawable() {
355            return new AnimatedVectorDrawable(this, null, null);
356        }
357
358        @Override
359        public Drawable newDrawable(Resources res) {
360            return new AnimatedVectorDrawable(this, res, null);
361        }
362
363        @Override
364        public Drawable newDrawable(Resources res, Theme theme) {
365            return new AnimatedVectorDrawable(this, res, theme);
366        }
367
368        @Override
369        public int getChangingConfigurations() {
370            return mChangingConfigurations;
371        }
372    }
373
374    private void setupAnimatorsForTarget(String name, Animator animator) {
375        Object target = mAnimatedVectorState.mVectorDrawable.getTargetByName(name);
376        animator.setTarget(target);
377        if (mAnimatedVectorState.mAnimators == null) {
378            mAnimatedVectorState.mAnimators = new ArrayList<Animator>();
379            mAnimatedVectorState.mTargetNameMap = new ArrayMap<Animator, String>();
380        }
381        mAnimatedVectorState.mAnimators.add(animator);
382        mAnimatedVectorState.mTargetNameMap.put(animator, name);
383        if (DBG_ANIMATION_VECTOR_DRAWABLE) {
384            Log.v(LOGTAG, "add animator  for target " + name + " " + animator);
385        }
386    }
387
388    @Override
389    public boolean isRunning() {
390        final ArrayList<Animator> animators = mAnimatedVectorState.mAnimators;
391        final int size = animators.size();
392        for (int i = 0; i < size; i++) {
393            final Animator animator = animators.get(i);
394            if (animator.isRunning()) {
395                return true;
396            }
397        }
398        return false;
399    }
400
401    private boolean isStarted() {
402        final ArrayList<Animator> animators = mAnimatedVectorState.mAnimators;
403        final int size = animators.size();
404        for (int i = 0; i < size; i++) {
405            final Animator animator = animators.get(i);
406            if (animator.isStarted()) {
407                return true;
408            }
409        }
410        return false;
411    }
412
413    @Override
414    public void start() {
415        final ArrayList<Animator> animators = mAnimatedVectorState.mAnimators;
416        final int size = animators.size();
417        for (int i = 0; i < size; i++) {
418            final Animator animator = animators.get(i);
419            if (!animator.isStarted()) {
420                animator.start();
421            }
422        }
423        invalidateSelf();
424    }
425
426    @Override
427    public void stop() {
428        final ArrayList<Animator> animators = mAnimatedVectorState.mAnimators;
429        final int size = animators.size();
430        for (int i = 0; i < size; i++) {
431            final Animator animator = animators.get(i);
432            animator.end();
433        }
434    }
435
436    /**
437     * Reverses ongoing animations or starts pending animations in reverse.
438     * <p>
439     * NOTE: Only works of all animations are ValueAnimators.
440     * @hide
441     */
442    public void reverse() {
443        final ArrayList<Animator> animators = mAnimatedVectorState.mAnimators;
444        final int size = animators.size();
445        for (int i = 0; i < size; i++) {
446            final Animator animator = animators.get(i);
447            if (animator.canReverse()) {
448                animator.reverse();
449            } else {
450                Log.w(LOGTAG, "AnimatedVectorDrawable can't reverse()");
451            }
452        }
453    }
454
455    /**
456     * @hide
457     */
458    public boolean canReverse() {
459        final ArrayList<Animator> animators = mAnimatedVectorState.mAnimators;
460        final int size = animators.size();
461        for (int i = 0; i < size; i++) {
462            final Animator animator = animators.get(i);
463            if (!animator.canReverse()) {
464                return false;
465            }
466        }
467        return true;
468    }
469}
470