AnimationDrawable.java revision 4b17118aca1e67963254ab83504b0753a3eac7ce
1/*
2 * Copyright (C) 2006 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 */
16
17package android.graphics.drawable;
18
19import java.io.IOException;
20
21import org.xmlpull.v1.XmlPullParser;
22import org.xmlpull.v1.XmlPullParserException;
23
24import android.content.res.Resources;
25import android.content.res.TypedArray;
26import android.content.res.Resources.Theme;
27import android.os.SystemClock;
28import android.util.AttributeSet;
29
30/**
31 * An object used to create frame-by-frame animations, defined by a series of Drawable objects,
32 * which can be used as a View object's background.
33 * <p>
34 * The simplest way to create a frame-by-frame animation is to define the animation in an XML
35 * file, placed in the res/drawable/ folder, and set it as the background to a View object. Then, call
36 * {@link #start()} to run the animation.
37 * <p>
38 * An AnimationDrawable defined in XML consists of a single <code>&lt;animation-list></code> element,
39 * and a series of nested <code>&lt;item></code> tags. Each item defines a frame of the animation.
40 * See the example below.
41 * </p>
42 * <p>spin_animation.xml file in res/drawable/ folder:</p>
43 * <pre>&lt;!-- Animation frames are wheel0.png -- wheel5.png files inside the
44 * res/drawable/ folder --&gt;
45 * &lt;animation-list android:id=&quot;@+id/selected&quot; android:oneshot=&quot;false&quot;&gt;
46 *    &lt;item android:drawable=&quot;@drawable/wheel0&quot; android:duration=&quot;50&quot; /&gt;
47 *    &lt;item android:drawable=&quot;@drawable/wheel1&quot; android:duration=&quot;50&quot; /&gt;
48 *    &lt;item android:drawable=&quot;@drawable/wheel2&quot; android:duration=&quot;50&quot; /&gt;
49 *    &lt;item android:drawable=&quot;@drawable/wheel3&quot; android:duration=&quot;50&quot; /&gt;
50 *    &lt;item android:drawable=&quot;@drawable/wheel4&quot; android:duration=&quot;50&quot; /&gt;
51 *    &lt;item android:drawable=&quot;@drawable/wheel5&quot; android:duration=&quot;50&quot; /&gt;
52 * &lt;/animation-list&gt;</pre>
53 *
54 * <p>Here is the code to load and play this animation.</p>
55 * <pre>
56 * // Load the ImageView that will host the animation and
57 * // set its background to our AnimationDrawable XML resource.
58 * ImageView img = (ImageView)findViewById(R.id.spinning_wheel_image);
59 * img.setBackgroundResource(R.drawable.spin_animation);
60 *
61 * // Get the background, which has been compiled to an AnimationDrawable object.
62 * AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
63 *
64 * // Start the animation (looped playback by default).
65 * frameAnimation.start();
66 * </pre>
67 *
68 * <div class="special reference">
69 * <h3>Developer Guides</h3>
70 * <p>For more information about animating with {@code AnimationDrawable}, read the
71 * <a href="{@docRoot}guide/topics/graphics/drawable-animation.html">Drawable Animation</a>
72 * developer guide.</p>
73 * </div>
74 *
75 * @attr ref android.R.styleable#AnimationDrawable_visible
76 * @attr ref android.R.styleable#AnimationDrawable_variablePadding
77 * @attr ref android.R.styleable#AnimationDrawable_oneshot
78 * @attr ref android.R.styleable#AnimationDrawableItem_duration
79 * @attr ref android.R.styleable#AnimationDrawableItem_drawable
80 */
81public class AnimationDrawable extends DrawableContainer implements Runnable, Animatable {
82    private final AnimationState mAnimationState;
83    private int mCurFrame = -1;
84    private boolean mAnimating;
85    private boolean mMutated;
86
87    public AnimationDrawable() {
88        this(null, null);
89    }
90
91    @Override
92    public boolean setVisible(boolean visible, boolean restart) {
93        final boolean changed = super.setVisible(visible, restart);
94        if (visible) {
95            if (changed || restart) {
96                setFrame(0, true, mAnimating);
97            }
98        } else {
99            unscheduleSelf(this);
100        }
101        return changed;
102    }
103
104    /**
105     * <p>Starts the animation, looping if necessary. This method has no effect
106     * if the animation is running. Do not call this in the {@link android.app.Activity#onCreate}
107     * method of your activity, because the {@link android.graphics.drawable.AnimationDrawable} is
108     * not yet fully attached to the window. If you want to play
109     * the animation immediately, without requiring interaction, then you might want to call it
110     * from the {@link android.app.Activity#onWindowFocusChanged} method in your activity,
111     * which will get called when Android brings your window into focus.</p>
112     *
113     * @see #isRunning()
114     * @see #stop()
115     */
116    @Override
117    public void start() {
118        if (!isRunning()) {
119            run();
120        }
121    }
122
123    /**
124     * <p>Stops the animation. This method has no effect if the animation is
125     * not running.</p>
126     *
127     * @see #isRunning()
128     * @see #start()
129     */
130    @Override
131    public void stop() {
132        if (isRunning()) {
133            unscheduleSelf(this);
134        }
135    }
136
137    /**
138     * <p>Indicates whether the animation is currently running or not.</p>
139     *
140     * @return true if the animation is running, false otherwise
141     */
142    @Override
143    public boolean isRunning() {
144        return mAnimating;
145    }
146
147    /**
148     * <p>This method exists for implementation purpose only and should not be
149     * called directly. Invoke {@link #start()} instead.</p>
150     *
151     * @see #start()
152     */
153    @Override
154    public void run() {
155        nextFrame(false);
156    }
157
158    @Override
159    public void unscheduleSelf(Runnable what) {
160        mCurFrame = -1;
161        mAnimating = false;
162        super.unscheduleSelf(what);
163    }
164
165    /**
166     * @return The number of frames in the animation
167     */
168    public int getNumberOfFrames() {
169        return mAnimationState.getChildCount();
170    }
171
172    /**
173     * @return The Drawable at the specified frame index
174     */
175    public Drawable getFrame(int index) {
176        return mAnimationState.getChild(index);
177    }
178
179    /**
180     * @return The duration in milliseconds of the frame at the
181     * specified index
182     */
183    public int getDuration(int i) {
184        return mAnimationState.mDurations[i];
185    }
186
187    /**
188     * @return True of the animation will play once, false otherwise
189     */
190    public boolean isOneShot() {
191        return mAnimationState.mOneShot;
192    }
193
194    /**
195     * Sets whether the animation should play once or repeat.
196     *
197     * @param oneShot Pass true if the animation should only play once
198     */
199    public void setOneShot(boolean oneShot) {
200        mAnimationState.mOneShot = oneShot;
201    }
202
203    /**
204     * Add a frame to the animation
205     *
206     * @param frame The frame to add
207     * @param duration How long in milliseconds the frame should appear
208     */
209    public void addFrame(Drawable frame, int duration) {
210        mAnimationState.addFrame(frame, duration);
211        if (mCurFrame < 0) {
212            setFrame(0, true, false);
213        }
214    }
215
216    private void nextFrame(boolean unschedule) {
217        int next = mCurFrame+1;
218        final int N = mAnimationState.getChildCount();
219        if (next >= N) {
220            next = 0;
221        }
222        setFrame(next, unschedule, !mAnimationState.mOneShot || next < (N - 1));
223    }
224
225    private void setFrame(int frame, boolean unschedule, boolean animate) {
226        if (frame >= mAnimationState.getChildCount()) {
227            return;
228        }
229        mCurFrame = frame;
230        selectDrawable(frame);
231        if (unschedule || animate) {
232            unscheduleSelf(this);
233        }
234        if (animate) {
235            // Unscheduling may have clobbered these values; restore them
236            mCurFrame = frame;
237            mAnimating = true;
238            scheduleSelf(this, SystemClock.uptimeMillis() + mAnimationState.mDurations[frame]);
239        }
240    }
241
242    @Override
243    public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme)
244            throws XmlPullParserException, IOException {
245
246        TypedArray a = r.obtainAttributes(attrs,
247                com.android.internal.R.styleable.AnimationDrawable);
248
249        super.inflateWithAttributes(r, parser, a,
250                com.android.internal.R.styleable.AnimationDrawable_visible);
251
252        mAnimationState.setVariablePadding(a.getBoolean(
253                com.android.internal.R.styleable.AnimationDrawable_variablePadding, false));
254
255        mAnimationState.mOneShot = a.getBoolean(
256                com.android.internal.R.styleable.AnimationDrawable_oneshot, false);
257
258        a.recycle();
259
260        int type;
261
262        final int innerDepth = parser.getDepth()+1;
263        int depth;
264        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT &&
265                ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) {
266            if (type != XmlPullParser.START_TAG) {
267                continue;
268            }
269
270            if (depth > innerDepth || !parser.getName().equals("item")) {
271                continue;
272            }
273
274            a = r.obtainAttributes(attrs, com.android.internal.R.styleable.AnimationDrawableItem);
275            int duration = a.getInt(
276                    com.android.internal.R.styleable.AnimationDrawableItem_duration, -1);
277            if (duration < 0) {
278                throw new XmlPullParserException(
279                        parser.getPositionDescription()
280                        + ": <item> tag requires a 'duration' attribute");
281            }
282            int drawableRes = a.getResourceId(
283                    com.android.internal.R.styleable.AnimationDrawableItem_drawable, 0);
284
285            a.recycle();
286
287            Drawable dr;
288            if (drawableRes != 0) {
289                dr = r.getDrawable(drawableRes);
290            } else {
291                while ((type=parser.next()) == XmlPullParser.TEXT) {
292                    // Empty
293                }
294                if (type != XmlPullParser.START_TAG) {
295                    throw new XmlPullParserException(parser.getPositionDescription() +
296                            ": <item> tag requires a 'drawable' attribute or child tag" +
297                            " defining a drawable");
298                }
299                dr = Drawable.createFromXmlInner(r, parser, attrs, theme);
300            }
301
302            mAnimationState.addFrame(dr, duration);
303            if (dr != null) {
304                dr.setCallback(this);
305            }
306        }
307
308        setFrame(0, true, false);
309    }
310
311    @Override
312    public Drawable mutate() {
313        if (!mMutated && super.mutate() == this) {
314            mAnimationState.mDurations = mAnimationState.mDurations.clone();
315            mMutated = true;
316        }
317        return this;
318    }
319
320    private final static class AnimationState extends DrawableContainerState {
321        private int[] mDurations;
322        private boolean mOneShot;
323
324        AnimationState(AnimationState orig, AnimationDrawable owner,
325                Resources res) {
326            super(orig, owner, res);
327
328            if (orig != null) {
329                mDurations = orig.mDurations;
330                mOneShot = orig.mOneShot;
331            } else {
332                mDurations = new int[getCapacity()];
333                mOneShot = true;
334            }
335        }
336
337        @Override
338        public Drawable newDrawable() {
339            return new AnimationDrawable(this, null);
340        }
341
342        @Override
343        public Drawable newDrawable(Resources res) {
344            return new AnimationDrawable(this, res);
345        }
346
347        public void addFrame(Drawable dr, int dur) {
348            // Do not combine the following. The array index must be evaluated before
349            // the array is accessed because super.addChild(dr) has a side effect on mDurations.
350            int pos = super.addChild(dr);
351            mDurations[pos] = dur;
352        }
353
354        @Override
355        public void growArray(int oldSize, int newSize) {
356            super.growArray(oldSize, newSize);
357            int[] newDurations = new int[newSize];
358            System.arraycopy(mDurations, 0, newDurations, 0, oldSize);
359            mDurations = newDurations;
360        }
361    }
362
363    private AnimationDrawable(AnimationState state, Resources res) {
364        AnimationState as = new AnimationState(state, this, res);
365        mAnimationState = as;
366        setConstantState(as);
367        if (state != null) {
368            setFrame(0, true, false);
369        }
370    }
371}
372
373