AnimatorInflater.java revision 7f9988f0f51e181f20fa22e17635d61893e5b74a
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.animation;
17
18import android.content.Context;
19import android.content.res.Resources;
20import android.content.res.Resources.NotFoundException;
21import android.content.res.Resources.Theme;
22import android.content.res.TypedArray;
23import android.content.res.XmlResourceParser;
24import android.graphics.Path;
25import android.util.AttributeSet;
26import android.util.Log;
27import android.util.PathParser;
28import android.util.StateSet;
29import android.util.TypedValue;
30import android.util.Xml;
31import android.view.InflateException;
32import android.view.animation.AnimationUtils;
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 is used to instantiate animator XML files into Animator objects.
44 * <p>
45 * For performance reasons, inflation relies heavily on pre-processing of
46 * XML files that is done at build time. Therefore, it is not currently possible
47 * to use this inflater with an XmlPullParser over a plain XML file at runtime;
48 * it only works with an XmlPullParser returned from a compiled resource (R.
49 * <em>something</em> file.)
50 */
51public class AnimatorInflater {
52    private static final String TAG = "AnimatorInflater";
53    /**
54     * These flags are used when parsing AnimatorSet objects
55     */
56    private static final int TOGETHER = 0;
57    private static final int SEQUENTIALLY = 1;
58
59    /**
60     * Enum values used in XML attributes to indicate the value for mValueType
61     */
62    private static final int VALUE_TYPE_FLOAT       = 0;
63    private static final int VALUE_TYPE_INT         = 1;
64    private static final int VALUE_TYPE_PATH        = 2;
65    private static final int VALUE_TYPE_COLOR       = 4;
66    private static final int VALUE_TYPE_CUSTOM      = 5;
67
68    private static final boolean DBG_ANIMATOR_INFLATER = false;
69
70    /**
71     * Loads an {@link Animator} object from a resource
72     *
73     * @param context Application context used to access resources
74     * @param id The resource id of the animation to load
75     * @return The animator object reference by the specified id
76     * @throws android.content.res.Resources.NotFoundException when the animation cannot be loaded
77     */
78    public static Animator loadAnimator(Context context, int id)
79            throws NotFoundException {
80        return loadAnimator(context.getResources(), context.getTheme(), id);
81    }
82
83    /**
84     * Loads an {@link Animator} object from a resource
85     *
86     * @param resources The resources
87     * @param theme The theme
88     * @param id The resource id of the animation to load
89     * @return The animator object reference by the specified id
90     * @throws android.content.res.Resources.NotFoundException when the animation cannot be loaded
91     * @hide
92     */
93    public static Animator loadAnimator(Resources resources, Theme theme, int id)
94            throws NotFoundException {
95
96        XmlResourceParser parser = null;
97        try {
98            parser = resources.getAnimation(id);
99            return createAnimatorFromXml(resources, theme, parser);
100        } catch (XmlPullParserException ex) {
101            Resources.NotFoundException rnf =
102                    new Resources.NotFoundException("Can't load animation resource ID #0x" +
103                    Integer.toHexString(id));
104            rnf.initCause(ex);
105            throw rnf;
106        } catch (IOException ex) {
107            Resources.NotFoundException rnf =
108                    new Resources.NotFoundException("Can't load animation resource ID #0x" +
109                    Integer.toHexString(id));
110            rnf.initCause(ex);
111            throw rnf;
112        } finally {
113            if (parser != null) parser.close();
114        }
115    }
116
117    public static StateListAnimator loadStateListAnimator(Context context, int id)
118            throws NotFoundException {
119        XmlResourceParser parser = null;
120        try {
121            parser = context.getResources().getAnimation(id);
122            return createStateListAnimatorFromXml(context, parser, Xml.asAttributeSet(parser));
123        } catch (XmlPullParserException ex) {
124            Resources.NotFoundException rnf =
125                    new Resources.NotFoundException(
126                            "Can't load state list animator resource ID #0x" +
127                                    Integer.toHexString(id)
128                    );
129            rnf.initCause(ex);
130            throw rnf;
131        } catch (IOException ex) {
132            Resources.NotFoundException rnf =
133                    new Resources.NotFoundException(
134                            "Can't load state list animator resource ID #0x" +
135                                    Integer.toHexString(id)
136                    );
137            rnf.initCause(ex);
138            throw rnf;
139        } finally {
140            if (parser != null) {
141                parser.close();
142            }
143        }
144    }
145
146    private static StateListAnimator createStateListAnimatorFromXml(Context context,
147            XmlPullParser parser, AttributeSet attributeSet)
148            throws IOException, XmlPullParserException {
149        int type;
150        StateListAnimator stateListAnimator = new StateListAnimator();
151
152        while (true) {
153            type = parser.next();
154            switch (type) {
155                case XmlPullParser.END_DOCUMENT:
156                case XmlPullParser.END_TAG:
157                    return stateListAnimator;
158
159                case XmlPullParser.START_TAG:
160                    // parse item
161                    Animator animator = null;
162                    if ("item".equals(parser.getName())) {
163                        int attributeCount = parser.getAttributeCount();
164                        int[] states = new int[attributeCount];
165                        int stateIndex = 0;
166                        for (int i = 0; i < attributeCount; i++) {
167                            int attrName = attributeSet.getAttributeNameResource(i);
168                            if (attrName == R.attr.animation) {
169                                animator = loadAnimator(context,
170                                        attributeSet.getAttributeResourceValue(i, 0));
171                            } else {
172                                states[stateIndex++] =
173                                        attributeSet.getAttributeBooleanValue(i, false) ?
174                                                attrName : -attrName;
175                            }
176
177                        }
178                        if (animator == null) {
179                            animator = createAnimatorFromXml(context.getResources(),
180                                    context.getTheme(), parser);
181                        }
182
183                        if (animator == null) {
184                            throw new Resources.NotFoundException(
185                                    "animation state item must have a valid animation");
186                        }
187                        stateListAnimator
188                                .addState(StateSet.trimStateSet(states, stateIndex), animator);
189
190                    }
191                    break;
192            }
193        }
194    }
195
196    /**
197     * PathDataEvaluator is used to interpolate between two paths which are
198     * represented in the same format but different control points' values.
199     * The path is represented as an array of PathDataNode here, which is
200     * fundamentally an array of floating point numbers.
201     */
202    private static class PathDataEvaluator implements TypeEvaluator<PathParser.PathDataNode[]> {
203        private PathParser.PathDataNode[] mNodeArray;
204
205        /**
206         * Create a PathParser.PathDataNode[] that does not reuse the animated value.
207         * Care must be taken when using this option because on every evaluation
208         * a new <code>PathParser.PathDataNode[]</code> will be allocated.
209         */
210        private PathDataEvaluator() {}
211
212        /**
213         * Create a PathDataEvaluator that reuses <code>nodeArray</code> for every evaluate() call.
214         * Caution must be taken to ensure that the value returned from
215         * {@link android.animation.ValueAnimator#getAnimatedValue()} is not cached, modified, or
216         * used across threads. The value will be modified on each <code>evaluate()</code> call.
217         *
218         * @param nodeArray The array to modify and return from <code>evaluate</code>.
219         */
220        public PathDataEvaluator(PathParser.PathDataNode[] nodeArray) {
221            mNodeArray = nodeArray;
222        }
223
224        @Override
225        public PathParser.PathDataNode[] evaluate(float fraction,
226                PathParser.PathDataNode[] startPathData,
227                PathParser.PathDataNode[] endPathData) {
228            if (!PathParser.canMorph(startPathData, endPathData)) {
229                throw new IllegalArgumentException("Can't interpolate between"
230                        + " two incompatible pathData");
231            }
232
233            if (mNodeArray == null || !PathParser.canMorph(mNodeArray, startPathData)) {
234                mNodeArray = PathParser.deepCopyNodes(startPathData);
235            }
236
237            for (int i = 0; i < startPathData.length; i++) {
238                mNodeArray[i].interpolatePathDataNode(startPathData[i],
239                        endPathData[i], fraction);
240            }
241
242            return mNodeArray;
243        }
244    }
245
246    /**
247     * @param anim The animator, must not be null
248     * @param arrayAnimator Incoming typed array for Animator's attributes.
249     * @param arrayObjectAnimator Incoming typed array for Object Animator's
250     *            attributes.
251     */
252    private static void parseAnimatorFromTypeArray(ValueAnimator anim,
253            TypedArray arrayAnimator, TypedArray arrayObjectAnimator) {
254        long duration = arrayAnimator.getInt(R.styleable.Animator_duration, 300);
255
256        long startDelay = arrayAnimator.getInt(R.styleable.Animator_startOffset, 0);
257
258        int valueType = arrayAnimator.getInt(R.styleable.Animator_valueType,
259                VALUE_TYPE_FLOAT);
260
261        TypeEvaluator evaluator = null;
262
263        boolean getFloats = (valueType == VALUE_TYPE_FLOAT);
264
265        TypedValue tvFrom = arrayAnimator.peekValue(R.styleable.Animator_valueFrom);
266        boolean hasFrom = (tvFrom != null);
267        int fromType = hasFrom ? tvFrom.type : 0;
268        TypedValue tvTo = arrayAnimator.peekValue(R.styleable.Animator_valueTo);
269        boolean hasTo = (tvTo != null);
270        int toType = hasTo ? tvTo.type : 0;
271
272        // TODO: Further clean up this part of code into 4 types : path, color,
273        // integer and float.
274        if (valueType == VALUE_TYPE_PATH) {
275            evaluator = setupAnimatorForPath(anim, arrayAnimator);
276        } else {
277            // Integer and float value types are handled here.
278            if ((hasFrom && (fromType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
279                    (fromType <= TypedValue.TYPE_LAST_COLOR_INT)) ||
280                    (hasTo && (toType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
281                            (toType <= TypedValue.TYPE_LAST_COLOR_INT))) {
282                // special case for colors: ignore valueType and get ints
283                getFloats = false;
284                evaluator = ArgbEvaluator.getInstance();
285            }
286            setupValues(anim, arrayAnimator, getFloats, hasFrom, fromType, hasTo, toType);
287        }
288
289        anim.setDuration(duration);
290        anim.setStartDelay(startDelay);
291
292        if (arrayAnimator.hasValue(R.styleable.Animator_repeatCount)) {
293            anim.setRepeatCount(
294                    arrayAnimator.getInt(R.styleable.Animator_repeatCount, 0));
295        }
296        if (arrayAnimator.hasValue(R.styleable.Animator_repeatMode)) {
297            anim.setRepeatMode(
298                    arrayAnimator.getInt(R.styleable.Animator_repeatMode,
299                            ValueAnimator.RESTART));
300        }
301        if (evaluator != null) {
302            anim.setEvaluator(evaluator);
303        }
304
305        if (arrayObjectAnimator != null) {
306            setupObjectAnimator(anim, arrayObjectAnimator, getFloats);
307        }
308    }
309
310    /**
311     * Setup the Animator to achieve path morphing.
312     *
313     * @param anim The target Animator which will be updated.
314     * @param arrayAnimator TypedArray for the ValueAnimator.
315     * @return the PathDataEvaluator.
316     */
317    private static TypeEvaluator setupAnimatorForPath(ValueAnimator anim,
318             TypedArray arrayAnimator) {
319        TypeEvaluator evaluator = null;
320        String fromString = arrayAnimator.getString(R.styleable.Animator_valueFrom);
321        String toString = arrayAnimator.getString(R.styleable.Animator_valueTo);
322        PathParser.PathDataNode[] nodesFrom = PathParser.createNodesFromPathData(fromString);
323        PathParser.PathDataNode[] nodesTo = PathParser.createNodesFromPathData(toString);
324
325        if (nodesFrom != null) {
326            if (nodesTo != null) {
327                anim.setObjectValues(nodesFrom, nodesTo);
328                if (!PathParser.canMorph(nodesFrom, nodesTo)) {
329                    throw new InflateException(arrayAnimator.getPositionDescription()
330                            + " Can't morph from " + fromString + " to " + toString);
331                }
332            } else {
333                anim.setObjectValues((Object)nodesFrom);
334            }
335            evaluator = new PathDataEvaluator(PathParser.deepCopyNodes(nodesFrom));
336        } else if (nodesTo != null) {
337            anim.setObjectValues((Object)nodesTo);
338            evaluator = new PathDataEvaluator(PathParser.deepCopyNodes(nodesTo));
339        }
340
341        if (DBG_ANIMATOR_INFLATER && evaluator != null) {
342            Log.v(TAG, "create a new PathDataEvaluator here");
343        }
344
345        return evaluator;
346    }
347
348    /**
349     * Setup ObjectAnimator's property or values from pathData.
350     *
351     * @param anim The target Animator which will be updated.
352     * @param arrayObjectAnimator TypedArray for the ObjectAnimator.
353     * @param getFloats True if the value type is float.
354     */
355    private static void setupObjectAnimator(ValueAnimator anim, TypedArray arrayObjectAnimator,
356            boolean getFloats) {
357        ObjectAnimator oa = (ObjectAnimator) anim;
358        String pathData = arrayObjectAnimator.getString(R.styleable.PropertyAnimator_pathData);
359
360        // Note that if there is a pathData defined in the Object Animator,
361        // valueFrom / valueTo will be ignored.
362        if (pathData != null) {
363            String propertyXName =
364                    arrayObjectAnimator.getString(R.styleable.PropertyAnimator_propertyXName);
365            String propertyYName =
366                    arrayObjectAnimator.getString(R.styleable.PropertyAnimator_propertyYName);
367
368            if (propertyXName == null && propertyYName == null) {
369                throw new InflateException(arrayObjectAnimator.getPositionDescription()
370                        + " propertyXName or propertyYName is needed for PathData");
371            } else {
372                Path path = PathParser.createPathFromPathData(pathData);
373                Keyframe[][] keyframes = PropertyValuesHolder.createKeyframes(path, !getFloats);
374                PropertyValuesHolder x = null;
375                PropertyValuesHolder y = null;
376                if (propertyXName != null) {
377                    x = PropertyValuesHolder.ofKeyframe(propertyXName, keyframes[0]);
378                }
379                if (propertyYName != null) {
380                    y = PropertyValuesHolder.ofKeyframe(propertyYName, keyframes[1]);
381                }
382                if (x == null) {
383                    oa.setValues(y);
384                } else if (y == null) {
385                    oa.setValues(x);
386                } else {
387                    oa.setValues(x, y);
388                }
389            }
390        } else {
391            String propertyName =
392                    arrayObjectAnimator.getString(R.styleable.PropertyAnimator_propertyName);
393            oa.setPropertyName(propertyName);
394        }
395    }
396
397    /**
398     * Setup ValueAnimator's values.
399     * This will handle all of the integer, float and color types.
400     *
401     * @param anim The target Animator which will be updated.
402     * @param arrayAnimator TypedArray for the ValueAnimator.
403     * @param getFloats True if the value type is float.
404     * @param hasFrom True if "valueFrom" exists.
405     * @param fromType The type of "valueFrom".
406     * @param hasTo True if "valueTo" exists.
407     * @param toType The type of "valueTo".
408     */
409    private static void setupValues(ValueAnimator anim, TypedArray arrayAnimator,
410            boolean getFloats, boolean hasFrom, int fromType, boolean hasTo, int toType) {
411        int valueFromIndex = R.styleable.Animator_valueFrom;
412        int valueToIndex = R.styleable.Animator_valueTo;
413        if (getFloats) {
414            float valueFrom;
415            float valueTo;
416            if (hasFrom) {
417                if (fromType == TypedValue.TYPE_DIMENSION) {
418                    valueFrom = arrayAnimator.getDimension(valueFromIndex, 0f);
419                } else {
420                    valueFrom = arrayAnimator.getFloat(valueFromIndex, 0f);
421                }
422                if (hasTo) {
423                    if (toType == TypedValue.TYPE_DIMENSION) {
424                        valueTo = arrayAnimator.getDimension(valueToIndex, 0f);
425                    } else {
426                        valueTo = arrayAnimator.getFloat(valueToIndex, 0f);
427                    }
428                    anim.setFloatValues(valueFrom, valueTo);
429                } else {
430                    anim.setFloatValues(valueFrom);
431                }
432            } else {
433                if (toType == TypedValue.TYPE_DIMENSION) {
434                    valueTo = arrayAnimator.getDimension(valueToIndex, 0f);
435                } else {
436                    valueTo = arrayAnimator.getFloat(valueToIndex, 0f);
437                }
438                anim.setFloatValues(valueTo);
439            }
440        } else {
441            int valueFrom;
442            int valueTo;
443            if (hasFrom) {
444                if (fromType == TypedValue.TYPE_DIMENSION) {
445                    valueFrom = (int) arrayAnimator.getDimension(valueFromIndex, 0f);
446                } else if ((fromType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
447                        (fromType <= TypedValue.TYPE_LAST_COLOR_INT)) {
448                    valueFrom = arrayAnimator.getColor(valueFromIndex, 0);
449                } else {
450                    valueFrom = arrayAnimator.getInt(valueFromIndex, 0);
451                }
452                if (hasTo) {
453                    if (toType == TypedValue.TYPE_DIMENSION) {
454                        valueTo = (int) arrayAnimator.getDimension(valueToIndex, 0f);
455                    } else if ((toType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
456                            (toType <= TypedValue.TYPE_LAST_COLOR_INT)) {
457                        valueTo = arrayAnimator.getColor(valueToIndex, 0);
458                    } else {
459                        valueTo = arrayAnimator.getInt(valueToIndex, 0);
460                    }
461                    anim.setIntValues(valueFrom, valueTo);
462                } else {
463                    anim.setIntValues(valueFrom);
464                }
465            } else {
466                if (hasTo) {
467                    if (toType == TypedValue.TYPE_DIMENSION) {
468                        valueTo = (int) arrayAnimator.getDimension(valueToIndex, 0f);
469                    } else if ((toType >= TypedValue.TYPE_FIRST_COLOR_INT) &&
470                            (toType <= TypedValue.TYPE_LAST_COLOR_INT)) {
471                        valueTo = arrayAnimator.getColor(valueToIndex, 0);
472                    } else {
473                        valueTo = arrayAnimator.getInt(valueToIndex, 0);
474                    }
475                    anim.setIntValues(valueTo);
476                }
477            }
478        }
479    }
480
481    private static Animator createAnimatorFromXml(Resources res, Theme theme, XmlPullParser parser)
482            throws XmlPullParserException, IOException {
483        return createAnimatorFromXml(res, theme, parser, Xml.asAttributeSet(parser), null, 0);
484    }
485
486    private static Animator createAnimatorFromXml(Resources res, Theme theme, XmlPullParser parser,
487            AttributeSet attrs, AnimatorSet parent, int sequenceOrdering)
488            throws XmlPullParserException, IOException {
489
490        Animator anim = null;
491        ArrayList<Animator> childAnims = null;
492
493        // Make sure we are on a start tag.
494        int type;
495        int depth = parser.getDepth();
496
497        while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
498                && type != XmlPullParser.END_DOCUMENT) {
499
500            if (type != XmlPullParser.START_TAG) {
501                continue;
502            }
503
504            String name = parser.getName();
505
506            if (name.equals("objectAnimator")) {
507                anim = loadObjectAnimator(res, theme, attrs);
508            } else if (name.equals("animator")) {
509                anim = loadAnimator(res, theme, attrs, null);
510            } else if (name.equals("set")) {
511                anim = new AnimatorSet();
512                TypedArray a;
513                if (theme != null) {
514                    a = theme.obtainStyledAttributes(attrs, R.styleable.AnimatorSet, 0, 0);
515                } else {
516                    a = res.obtainAttributes(attrs, R.styleable.AnimatorSet);
517                }
518                int ordering = a.getInt(R.styleable.AnimatorSet_ordering,
519                        TOGETHER);
520                createAnimatorFromXml(res, theme, parser, attrs, (AnimatorSet) anim, ordering);
521                a.recycle();
522            } else {
523                throw new RuntimeException("Unknown animator name: " + parser.getName());
524            }
525
526            if (parent != null) {
527                if (childAnims == null) {
528                    childAnims = new ArrayList<Animator>();
529                }
530                childAnims.add(anim);
531            }
532        }
533        if (parent != null && childAnims != null) {
534            Animator[] animsArray = new Animator[childAnims.size()];
535            int index = 0;
536            for (Animator a : childAnims) {
537                animsArray[index++] = a;
538            }
539            if (sequenceOrdering == TOGETHER) {
540                parent.playTogether(animsArray);
541            } else {
542                parent.playSequentially(animsArray);
543            }
544        }
545
546        return anim;
547
548    }
549
550    private static ObjectAnimator loadObjectAnimator(Resources res, Theme theme, AttributeSet attrs)
551            throws NotFoundException {
552        ObjectAnimator anim = new ObjectAnimator();
553
554        loadAnimator(res, theme, attrs, anim);
555
556        return anim;
557    }
558
559    /**
560     * Creates a new animation whose parameters come from the specified context
561     * and attributes set.
562     *
563     * @param res The resources
564     * @param attrs The set of attributes holding the animation parameters
565     * @param anim Null if this is a ValueAnimator, otherwise this is an
566     *            ObjectAnimator
567     */
568    private static ValueAnimator loadAnimator(Resources res, Theme theme,
569            AttributeSet attrs, ValueAnimator anim)
570            throws NotFoundException {
571
572        TypedArray arrayAnimator = null;
573        TypedArray arrayObjectAnimator = null;
574
575        if (theme != null) {
576            arrayAnimator = theme.obtainStyledAttributes(attrs, R.styleable.Animator, 0, 0);
577        } else {
578            arrayAnimator = res.obtainAttributes(attrs, R.styleable.Animator);
579        }
580
581        // If anim is not null, then it is an object animator.
582        if (anim != null) {
583            if (theme != null) {
584                arrayObjectAnimator = theme.obtainStyledAttributes(attrs,
585                        R.styleable.PropertyAnimator, 0, 0);
586            } else {
587                arrayObjectAnimator = res.obtainAttributes(attrs, R.styleable.PropertyAnimator);
588            }
589        }
590
591        if (anim == null) {
592            anim = new ValueAnimator();
593        }
594
595        parseAnimatorFromTypeArray(anim, arrayAnimator, arrayObjectAnimator);
596
597        final int resID =
598                arrayAnimator.getResourceId(R.styleable.Animator_interpolator, 0);
599        if (resID > 0) {
600            anim.setInterpolator(AnimationUtils.loadInterpolator(res, theme, resID));
601        }
602
603        arrayAnimator.recycle();
604        if (arrayObjectAnimator != null) {
605            arrayObjectAnimator.recycle();
606        }
607
608        return anim;
609    }
610}
611