AnimationDrawable.java revision 03d30a573b8bc8e169e153a0fffa053ffedcd5ee
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><animation-list></code> element, 39 * and a series of nested <code><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><!-- Animation frames are wheel0.png -- wheel5.png files inside the 44 * res/drawable/ folder --> 45 * <animation-list android:id="@+id/selected" android:oneshot="false"> 46 * <item android:drawable="@drawable/wheel0" android:duration="50" /> 47 * <item android:drawable="@drawable/wheel1" android:duration="50" /> 48 * <item android:drawable="@drawable/wheel2" android:duration="50" /> 49 * <item android:drawable="@drawable/wheel3" android:duration="50" /> 50 * <item android:drawable="@drawable/wheel4" android:duration="50" /> 51 * <item android:drawable="@drawable/wheel5" android:duration="50" /> 52 * </animation-list></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 84 /** The current frame, may be -1 when not animating. */ 85 private int mCurFrame = -1; 86 87 /** Whether the drawable has an animation callback posted. */ 88 private boolean mRunning; 89 90 /** Whether the drawable should animate when visible. */ 91 private boolean mAnimating; 92 93 private boolean mMutated; 94 95 public AnimationDrawable() { 96 this(null, null); 97 } 98 99 /** 100 * Sets whether this AnimationDrawable is visible. 101 * <p> 102 * When the drawable becomes invisible, it will pause its animation. A 103 * subsequent change to visible with <code>restart</code> set to true will 104 * restart the animation from the first frame. If <code>restart</code> is 105 * false, the animation will resume from the most recent frame. 106 * 107 * @param visible true if visible, false otherwise 108 * @param restart when visible, true to force the animation to restart 109 * from the first frame 110 * @return true if the new visibility is different than its previous state 111 */ 112 @Override 113 public boolean setVisible(boolean visible, boolean restart) { 114 final boolean changed = super.setVisible(visible, restart); 115 if (visible) { 116 if (restart || changed) { 117 setFrame(restart ? 0 : mCurFrame, true, mAnimating); 118 } 119 } else { 120 unscheduleSelf(this); 121 } 122 return changed; 123 } 124 125 /** 126 * <p>Starts the animation, looping if necessary. This method has no effect 127 * if the animation is running. Do not call this in the {@link android.app.Activity#onCreate} 128 * method of your activity, because the {@link android.graphics.drawable.AnimationDrawable} is 129 * not yet fully attached to the window. If you want to play 130 * the animation immediately, without requiring interaction, then you might want to call it 131 * from the {@link android.app.Activity#onWindowFocusChanged} method in your activity, 132 * which will get called when Android brings your window into focus.</p> 133 * 134 * @see #isRunning() 135 * @see #stop() 136 */ 137 @Override 138 public void start() { 139 mAnimating = true; 140 141 if (!isRunning()) { 142 run(); 143 } 144 } 145 146 /** 147 * <p>Stops the animation. This method has no effect if the animation is 148 * not running.</p> 149 * 150 * @see #isRunning() 151 * @see #start() 152 */ 153 @Override 154 public void stop() { 155 mAnimating = false; 156 157 if (isRunning()) { 158 unscheduleSelf(this); 159 } 160 } 161 162 /** 163 * <p>Indicates whether the animation is currently running or not.</p> 164 * 165 * @return true if the animation is running, false otherwise 166 */ 167 @Override 168 public boolean isRunning() { 169 return mRunning; 170 } 171 172 /** 173 * <p>This method exists for implementation purpose only and should not be 174 * called directly. Invoke {@link #start()} instead.</p> 175 * 176 * @see #start() 177 */ 178 @Override 179 public void run() { 180 nextFrame(false); 181 } 182 183 @Override 184 public void unscheduleSelf(Runnable what) { 185 mCurFrame = -1; 186 mRunning = false; 187 super.unscheduleSelf(what); 188 } 189 190 /** 191 * @return The number of frames in the animation 192 */ 193 public int getNumberOfFrames() { 194 return mAnimationState.getChildCount(); 195 } 196 197 /** 198 * @return The Drawable at the specified frame index 199 */ 200 public Drawable getFrame(int index) { 201 return mAnimationState.getChild(index); 202 } 203 204 /** 205 * @return The duration in milliseconds of the frame at the 206 * specified index 207 */ 208 public int getDuration(int i) { 209 return mAnimationState.mDurations[i]; 210 } 211 212 /** 213 * @return True of the animation will play once, false otherwise 214 */ 215 public boolean isOneShot() { 216 return mAnimationState.mOneShot; 217 } 218 219 /** 220 * Sets whether the animation should play once or repeat. 221 * 222 * @param oneShot Pass true if the animation should only play once 223 */ 224 public void setOneShot(boolean oneShot) { 225 mAnimationState.mOneShot = oneShot; 226 } 227 228 /** 229 * Add a frame to the animation 230 * 231 * @param frame The frame to add 232 * @param duration How long in milliseconds the frame should appear 233 */ 234 public void addFrame(Drawable frame, int duration) { 235 mAnimationState.addFrame(frame, duration); 236 if (mCurFrame < 0) { 237 setFrame(0, true, false); 238 } 239 } 240 241 private void nextFrame(boolean unschedule) { 242 int next = mCurFrame+1; 243 final int N = mAnimationState.getChildCount(); 244 if (next >= N) { 245 next = 0; 246 } 247 248 setFrame(next, unschedule, !mAnimationState.mOneShot || next < (N - 1)); 249 } 250 251 private void setFrame(int frame, boolean unschedule, boolean animate) { 252 if (frame >= mAnimationState.getChildCount()) { 253 return; 254 } 255 mAnimating = animate; 256 mCurFrame = frame; 257 selectDrawable(frame); 258 if (unschedule || animate) { 259 unscheduleSelf(this); 260 } 261 if (animate) { 262 // Unscheduling may have clobbered these values; restore them 263 mCurFrame = frame; 264 mRunning = true; 265 scheduleSelf(this, SystemClock.uptimeMillis() + mAnimationState.mDurations[frame]); 266 } 267 } 268 269 @Override 270 public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) 271 throws XmlPullParserException, IOException { 272 273 TypedArray a = r.obtainAttributes(attrs, 274 com.android.internal.R.styleable.AnimationDrawable); 275 276 super.inflateWithAttributes(r, parser, a, 277 com.android.internal.R.styleable.AnimationDrawable_visible); 278 279 mAnimationState.setVariablePadding(a.getBoolean( 280 com.android.internal.R.styleable.AnimationDrawable_variablePadding, false)); 281 282 mAnimationState.mOneShot = a.getBoolean( 283 com.android.internal.R.styleable.AnimationDrawable_oneshot, false); 284 285 a.recycle(); 286 287 int type; 288 289 final int innerDepth = parser.getDepth()+1; 290 int depth; 291 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT && 292 ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) { 293 if (type != XmlPullParser.START_TAG) { 294 continue; 295 } 296 297 if (depth > innerDepth || !parser.getName().equals("item")) { 298 continue; 299 } 300 301 a = r.obtainAttributes(attrs, com.android.internal.R.styleable.AnimationDrawableItem); 302 int duration = a.getInt( 303 com.android.internal.R.styleable.AnimationDrawableItem_duration, -1); 304 if (duration < 0) { 305 throw new XmlPullParserException( 306 parser.getPositionDescription() 307 + ": <item> tag requires a 'duration' attribute"); 308 } 309 int drawableRes = a.getResourceId( 310 com.android.internal.R.styleable.AnimationDrawableItem_drawable, 0); 311 312 a.recycle(); 313 314 Drawable dr; 315 if (drawableRes != 0) { 316 dr = r.getDrawable(drawableRes, theme); 317 } else { 318 while ((type=parser.next()) == XmlPullParser.TEXT) { 319 // Empty 320 } 321 if (type != XmlPullParser.START_TAG) { 322 throw new XmlPullParserException(parser.getPositionDescription() + 323 ": <item> tag requires a 'drawable' attribute or child tag" + 324 " defining a drawable"); 325 } 326 dr = Drawable.createFromXmlInner(r, parser, attrs, theme); 327 } 328 329 mAnimationState.addFrame(dr, duration); 330 if (dr != null) { 331 dr.setCallback(this); 332 } 333 } 334 335 setFrame(0, true, false); 336 } 337 338 @Override 339 public Drawable mutate() { 340 if (!mMutated && super.mutate() == this) { 341 mAnimationState.mDurations = mAnimationState.mDurations.clone(); 342 mMutated = true; 343 } 344 return this; 345 } 346 347 private final static class AnimationState extends DrawableContainerState { 348 private int[] mDurations; 349 private boolean mOneShot; 350 351 AnimationState(AnimationState orig, AnimationDrawable owner, 352 Resources res) { 353 super(orig, owner, res); 354 355 if (orig != null) { 356 mDurations = orig.mDurations; 357 mOneShot = orig.mOneShot; 358 } else { 359 mDurations = new int[getCapacity()]; 360 mOneShot = true; 361 } 362 } 363 364 @Override 365 public Drawable newDrawable() { 366 return new AnimationDrawable(this, null); 367 } 368 369 @Override 370 public Drawable newDrawable(Resources res) { 371 return new AnimationDrawable(this, res); 372 } 373 374 public void addFrame(Drawable dr, int dur) { 375 // Do not combine the following. The array index must be evaluated before 376 // the array is accessed because super.addChild(dr) has a side effect on mDurations. 377 int pos = super.addChild(dr); 378 mDurations[pos] = dur; 379 } 380 381 @Override 382 public void growArray(int oldSize, int newSize) { 383 super.growArray(oldSize, newSize); 384 int[] newDurations = new int[newSize]; 385 System.arraycopy(mDurations, 0, newDurations, 0, oldSize); 386 mDurations = newDurations; 387 } 388 } 389 390 private AnimationDrawable(AnimationState state, Resources res) { 391 AnimationState as = new AnimationState(state, this, res); 392 mAnimationState = as; 393 setConstantState(as); 394 if (state != null) { 395 setFrame(0, true, false); 396 } 397 } 398} 399 400