AnimatedStateListDrawable.java revision b067405bf453289a6b6bfd34b06700f08be58c24
1/* 2 * Copyright (C) 2014 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 android.animation.ObjectAnimator; 20import android.animation.TimeInterpolator; 21import android.annotation.NonNull; 22import android.annotation.Nullable; 23import android.content.res.Resources; 24import android.content.res.Resources.Theme; 25import android.content.res.TypedArray; 26import android.util.AttributeSet; 27import android.util.Log; 28import android.util.LongSparseLongArray; 29import android.util.SparseIntArray; 30import android.util.StateSet; 31 32import com.android.internal.R; 33 34import org.xmlpull.v1.XmlPullParser; 35import org.xmlpull.v1.XmlPullParserException; 36 37import java.io.IOException; 38 39/** 40 * Drawable containing a set of Drawable keyframes where the currently displayed 41 * keyframe is chosen based on the current state set. Animations between 42 * keyframes may optionally be defined using transition elements. 43 * <p> 44 * This drawable can be defined in an XML file with the <code> 45 * <animated-selector></code> element. Each keyframe Drawable is defined in a 46 * nested <code><item></code> element. Transitions are defined in a nested 47 * <code><transition></code> element. 48 * 49 * @attr ref android.R.styleable#DrawableStates_state_focused 50 * @attr ref android.R.styleable#DrawableStates_state_window_focused 51 * @attr ref android.R.styleable#DrawableStates_state_enabled 52 * @attr ref android.R.styleable#DrawableStates_state_checkable 53 * @attr ref android.R.styleable#DrawableStates_state_checked 54 * @attr ref android.R.styleable#DrawableStates_state_selected 55 * @attr ref android.R.styleable#DrawableStates_state_activated 56 * @attr ref android.R.styleable#DrawableStates_state_active 57 * @attr ref android.R.styleable#DrawableStates_state_single 58 * @attr ref android.R.styleable#DrawableStates_state_first 59 * @attr ref android.R.styleable#DrawableStates_state_middle 60 * @attr ref android.R.styleable#DrawableStates_state_last 61 * @attr ref android.R.styleable#DrawableStates_state_pressed 62 */ 63public class AnimatedStateListDrawable extends StateListDrawable { 64 private static final String LOGTAG = AnimatedStateListDrawable.class.getSimpleName(); 65 66 private static final String ELEMENT_TRANSITION = "transition"; 67 private static final String ELEMENT_ITEM = "item"; 68 69 private AnimatedStateListState mState; 70 71 /** The currently running transition, if any. */ 72 private Transition mTransition; 73 74 /** Index to be set after the transition ends. */ 75 private int mTransitionToIndex = -1; 76 77 /** Index away from which we are transitioning. */ 78 private int mTransitionFromIndex = -1; 79 80 private boolean mMutated; 81 82 public AnimatedStateListDrawable() { 83 this(null, null); 84 } 85 86 @Override 87 public boolean setVisible(boolean visible, boolean restart) { 88 final boolean changed = super.setVisible(visible, restart); 89 90 if (mTransition != null && (changed || restart)) { 91 if (visible) { 92 mTransition.start(); 93 } else { 94 // Ensure we're showing the correct state when visible. 95 jumpToCurrentState(); 96 } 97 } 98 99 return changed; 100 } 101 102 /** 103 * Add a new drawable to the set of keyframes. 104 * 105 * @param stateSet An array of resource IDs to associate with the keyframe 106 * @param drawable The drawable to show when in the specified state, may not be null 107 * @param id The unique identifier for the keyframe 108 */ 109 public void addState(@NonNull int[] stateSet, @NonNull Drawable drawable, int id) { 110 if (drawable == null) { 111 throw new IllegalArgumentException("Drawable must not be null"); 112 } 113 114 mState.addStateSet(stateSet, drawable, id); 115 onStateChange(getState()); 116 } 117 118 /** 119 * Adds a new transition between keyframes. 120 * 121 * @param fromId Unique identifier of the starting keyframe 122 * @param toId Unique identifier of the ending keyframe 123 * @param transition An {@link Animatable} drawable to use as a transition, may not be null 124 * @param reversible Whether the transition can be reversed 125 */ 126 public <T extends Drawable & Animatable> void addTransition(int fromId, int toId, 127 @NonNull T transition, boolean reversible) { 128 if (transition == null) { 129 throw new IllegalArgumentException("Transition drawable must not be null"); 130 } 131 132 mState.addTransition(fromId, toId, transition, reversible); 133 } 134 135 @Override 136 public boolean isStateful() { 137 return true; 138 } 139 140 @Override 141 protected boolean onStateChange(int[] stateSet) { 142 final int keyframeIndex = mState.indexOfKeyframe(stateSet); 143 if (keyframeIndex == getCurrentIndex()) { 144 // Propagate state change to current keyframe. 145 final Drawable current = getCurrent(); 146 if (current != null) { 147 return current.setState(stateSet); 148 } 149 return false; 150 } 151 152 // Attempt to find a valid transition to the keyframe. 153 if (selectTransition(keyframeIndex)) { 154 return true; 155 } 156 157 // No valid transition, attempt to jump directly to the keyframe. 158 if (selectDrawable(keyframeIndex)) { 159 return true; 160 } 161 162 return super.onStateChange(stateSet); 163 } 164 165 private boolean selectTransition(int toIndex) { 166 final int fromIndex; 167 final Transition currentTransition = mTransition; 168 if (currentTransition != null) { 169 if (toIndex == mTransitionToIndex) { 170 // Already animating to that keyframe. 171 return true; 172 } else if (toIndex == mTransitionFromIndex && currentTransition.canReverse()) { 173 // Reverse the current animation. 174 currentTransition.reverse(); 175 mTransitionToIndex = mTransitionFromIndex; 176 mTransitionFromIndex = toIndex; 177 return true; 178 } 179 180 // Start the next transition from the end of the current one. 181 fromIndex = mTransitionToIndex; 182 183 // Changing animation, end the current animation. 184 currentTransition.stop(); 185 } else { 186 fromIndex = getCurrentIndex(); 187 } 188 189 // Reset state. 190 mTransition = null; 191 mTransitionFromIndex = -1; 192 mTransitionToIndex = -1; 193 194 final AnimatedStateListState state = mState; 195 final int fromId = state.getKeyframeIdAt(fromIndex); 196 final int toId = state.getKeyframeIdAt(toIndex); 197 if (toId == 0 || fromId == 0) { 198 // Missing a keyframe ID. 199 return false; 200 } 201 202 final int transitionIndex = state.indexOfTransition(fromId, toId); 203 if (transitionIndex < 0) { 204 // Couldn't select a transition. 205 return false; 206 } 207 208 // This may fail if we're already on the transition, but that's okay! 209 selectDrawable(transitionIndex); 210 211 final Transition transition; 212 final Drawable d = getCurrent(); 213 if (d instanceof AnimationDrawable) { 214 final boolean reversed = state.isTransitionReversed(fromId, toId); 215 transition = new AnimationDrawableTransition((AnimationDrawable) d, reversed); 216 } else if (d instanceof AnimatedVectorDrawable) { 217 final boolean reversed = state.isTransitionReversed(fromId, toId); 218 transition = new AnimatedVectorDrawableTransition((AnimatedVectorDrawable) d, reversed); 219 } else if (d instanceof Animatable) { 220 transition = new AnimatableTransition((Animatable) d); 221 } else { 222 // We don't know how to animate this transition. 223 return false; 224 } 225 226 transition.start(); 227 228 mTransition = transition; 229 mTransitionFromIndex = fromIndex; 230 mTransitionToIndex = toIndex; 231 return true; 232 } 233 234 private static abstract class Transition { 235 public abstract void start(); 236 public abstract void stop(); 237 238 public void reverse() { 239 // Not supported by default. 240 } 241 242 public boolean canReverse() { 243 return false; 244 } 245 } 246 247 private static class AnimatableTransition extends Transition { 248 private final Animatable mA; 249 250 public AnimatableTransition(Animatable a) { 251 mA = a; 252 } 253 254 @Override 255 public void start() { 256 mA.start(); 257 } 258 259 @Override 260 public void stop() { 261 mA.stop(); 262 } 263 } 264 265 266 private static class AnimationDrawableTransition extends Transition { 267 private final ObjectAnimator mAnim; 268 269 public AnimationDrawableTransition(AnimationDrawable ad, boolean reversed) { 270 final int frameCount = ad.getNumberOfFrames(); 271 final int fromFrame = reversed ? frameCount - 1 : 0; 272 final int toFrame = reversed ? 0 : frameCount - 1; 273 final FrameInterpolator interp = new FrameInterpolator(ad, reversed); 274 final ObjectAnimator anim = ObjectAnimator.ofInt(ad, "currentIndex", fromFrame, toFrame); 275 anim.setAutoCancel(true); 276 anim.setDuration(interp.getTotalDuration()); 277 anim.setInterpolator(interp); 278 279 mAnim = anim; 280 } 281 282 @Override 283 public boolean canReverse() { 284 return true; 285 } 286 287 @Override 288 public void start() { 289 mAnim.start(); 290 } 291 292 @Override 293 public void reverse() { 294 mAnim.reverse(); 295 } 296 297 @Override 298 public void stop() { 299 mAnim.cancel(); 300 } 301 } 302 303 private static class AnimatedVectorDrawableTransition extends Transition { 304 private final AnimatedVectorDrawable mAvd; 305 private final boolean mReversed; 306 307 public AnimatedVectorDrawableTransition(AnimatedVectorDrawable avd, boolean reversed) { 308 mAvd = avd; 309 mReversed = reversed; 310 } 311 312 @Override 313 public boolean canReverse() { 314 return mAvd.canReverse(); 315 } 316 317 @Override 318 public void start() { 319 if (mReversed) { 320 reverse(); 321 } else { 322 mAvd.start(); 323 } 324 } 325 326 @Override 327 public void reverse() { 328 if (canReverse()) { 329 mAvd.reverse(); 330 } else { 331 Log.w(LOGTAG, "Reverse() is called on a drawable can't reverse"); 332 } 333 } 334 335 @Override 336 public void stop() { 337 mAvd.stop(); 338 } 339 } 340 341 342 @Override 343 public void jumpToCurrentState() { 344 super.jumpToCurrentState(); 345 346 if (mTransition != null) { 347 mTransition.stop(); 348 mTransition = null; 349 350 selectDrawable(mTransitionToIndex); 351 mTransitionToIndex = -1; 352 mTransitionFromIndex = -1; 353 } 354 } 355 356 @Override 357 public void inflate(@NonNull Resources r, @NonNull XmlPullParser parser, 358 @NonNull AttributeSet attrs, @Nullable Theme theme) 359 throws XmlPullParserException, IOException { 360 final TypedArray a = r.obtainAttributes(attrs, R.styleable.AnimatedStateListDrawable); 361 362 super.inflateWithAttributes(r, parser, a, R.styleable.AnimatedStateListDrawable_visible); 363 364 final StateListState stateListState = getStateListState(); 365 stateListState.setVariablePadding(a.getBoolean( 366 R.styleable.AnimatedStateListDrawable_variablePadding, false)); 367 stateListState.setConstantSize(a.getBoolean( 368 R.styleable.AnimatedStateListDrawable_constantSize, false)); 369 stateListState.setEnterFadeDuration(a.getInt( 370 R.styleable.AnimatedStateListDrawable_enterFadeDuration, 0)); 371 stateListState.setExitFadeDuration(a.getInt( 372 R.styleable.AnimatedStateListDrawable_exitFadeDuration, 0)); 373 374 setDither(a.getBoolean(R.styleable.AnimatedStateListDrawable_dither, true)); 375 setAutoMirrored(a.getBoolean(R.styleable.AnimatedStateListDrawable_autoMirrored, false)); 376 377 a.recycle(); 378 379 int type; 380 381 final int innerDepth = parser.getDepth() + 1; 382 int depth; 383 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 384 && ((depth = parser.getDepth()) >= innerDepth 385 || type != XmlPullParser.END_TAG)) { 386 if (type != XmlPullParser.START_TAG) { 387 continue; 388 } 389 390 if (depth > innerDepth) { 391 continue; 392 } 393 394 if (parser.getName().equals(ELEMENT_ITEM)) { 395 parseItem(r, parser, attrs, theme); 396 } else if (parser.getName().equals(ELEMENT_TRANSITION)) { 397 parseTransition(r, parser, attrs, theme); 398 } 399 } 400 401 onStateChange(getState()); 402 } 403 404 private int parseTransition(@NonNull Resources r, @NonNull XmlPullParser parser, 405 @NonNull AttributeSet attrs, @Nullable Theme theme) 406 throws XmlPullParserException, IOException { 407 int drawableRes = 0; 408 int fromId = 0; 409 int toId = 0; 410 boolean reversible = false; 411 412 final int numAttrs = attrs.getAttributeCount(); 413 for (int i = 0; i < numAttrs; i++) { 414 final int stateResId = attrs.getAttributeNameResource(i); 415 switch (stateResId) { 416 case 0: 417 break; 418 case R.attr.fromId: 419 fromId = attrs.getAttributeResourceValue(i, 0); 420 break; 421 case R.attr.toId: 422 toId = attrs.getAttributeResourceValue(i, 0); 423 break; 424 case R.attr.drawable: 425 drawableRes = attrs.getAttributeResourceValue(i, 0); 426 break; 427 case R.attr.reversible: 428 reversible = attrs.getAttributeBooleanValue(i, false); 429 break; 430 } 431 } 432 433 final Drawable dr; 434 if (drawableRes != 0) { 435 dr = r.getDrawable(drawableRes, theme); 436 } else { 437 int type; 438 while ((type = parser.next()) == XmlPullParser.TEXT) { 439 } 440 if (type != XmlPullParser.START_TAG) { 441 throw new XmlPullParserException( 442 parser.getPositionDescription() 443 + ": <item> tag requires a 'drawable' attribute or " 444 + "child tag defining a drawable"); 445 } 446 dr = Drawable.createFromXmlInner(r, parser, attrs, theme); 447 } 448 449 return mState.addTransition(fromId, toId, dr, reversible); 450 } 451 452 private int parseItem(@NonNull Resources r, @NonNull XmlPullParser parser, 453 @NonNull AttributeSet attrs, @Nullable Theme theme) 454 throws XmlPullParserException, IOException { 455 int drawableRes = 0; 456 int keyframeId = 0; 457 458 int j = 0; 459 final int numAttrs = attrs.getAttributeCount(); 460 int[] states = new int[numAttrs]; 461 for (int i = 0; i < numAttrs; i++) { 462 final int stateResId = attrs.getAttributeNameResource(i); 463 switch (stateResId) { 464 case 0: 465 break; 466 case R.attr.id: 467 keyframeId = attrs.getAttributeResourceValue(i, 0); 468 break; 469 case R.attr.drawable: 470 drawableRes = attrs.getAttributeResourceValue(i, 0); 471 break; 472 default: 473 final boolean hasState = attrs.getAttributeBooleanValue(i, false); 474 states[j++] = hasState ? stateResId : -stateResId; 475 } 476 } 477 states = StateSet.trimStateSet(states, j); 478 479 final Drawable dr; 480 if (drawableRes != 0) { 481 dr = r.getDrawable(drawableRes, theme); 482 } else { 483 int type; 484 while ((type = parser.next()) == XmlPullParser.TEXT) { 485 } 486 if (type != XmlPullParser.START_TAG) { 487 throw new XmlPullParserException( 488 parser.getPositionDescription() 489 + ": <item> tag requires a 'drawable' attribute or " 490 + "child tag defining a drawable"); 491 } 492 dr = Drawable.createFromXmlInner(r, parser, attrs, theme); 493 } 494 495 return mState.addStateSet(states, dr, keyframeId); 496 } 497 498 @Override 499 public Drawable mutate() { 500 if (!mMutated && super.mutate() == this) { 501 final AnimatedStateListState newState = new AnimatedStateListState(mState, this, null); 502 setConstantState(newState); 503 mMutated = true; 504 } 505 506 return this; 507 } 508 509 static class AnimatedStateListState extends StateListState { 510 private static final int REVERSE_SHIFT = 32; 511 private static final int REVERSE_MASK = 0x1; 512 513 final LongSparseLongArray mTransitions; 514 final SparseIntArray mStateIds; 515 516 AnimatedStateListState(@Nullable AnimatedStateListState orig, 517 @NonNull AnimatedStateListDrawable owner, @Nullable Resources res) { 518 super(orig, owner, res); 519 520 if (orig != null) { 521 mTransitions = orig.mTransitions.clone(); 522 mStateIds = orig.mStateIds.clone(); 523 } else { 524 mTransitions = new LongSparseLongArray(); 525 mStateIds = new SparseIntArray(); 526 } 527 } 528 529 int addTransition(int fromId, int toId, @NonNull Drawable anim, boolean reversible) { 530 final int pos = super.addChild(anim); 531 final long keyFromTo = generateTransitionKey(fromId, toId); 532 mTransitions.append(keyFromTo, pos); 533 534 if (reversible) { 535 final long keyToFrom = generateTransitionKey(toId, fromId); 536 mTransitions.append(keyToFrom, pos | (1L << REVERSE_SHIFT)); 537 } 538 539 return addChild(anim); 540 } 541 542 int addStateSet(@NonNull int[] stateSet, @NonNull Drawable drawable, int id) { 543 final int index = super.addStateSet(stateSet, drawable); 544 mStateIds.put(index, id); 545 return index; 546 } 547 548 int indexOfKeyframe(@NonNull int[] stateSet) { 549 final int index = super.indexOfStateSet(stateSet); 550 if (index >= 0) { 551 return index; 552 } 553 554 return super.indexOfStateSet(StateSet.WILD_CARD); 555 } 556 557 int getKeyframeIdAt(int index) { 558 return index < 0 ? 0 : mStateIds.get(index, 0); 559 } 560 561 int indexOfTransition(int fromId, int toId) { 562 final long keyFromTo = generateTransitionKey(fromId, toId); 563 return (int) mTransitions.get(keyFromTo, -1); 564 } 565 566 boolean isTransitionReversed(int fromId, int toId) { 567 final long keyFromTo = generateTransitionKey(fromId, toId); 568 return (mTransitions.get(keyFromTo, -1) >> REVERSE_SHIFT & REVERSE_MASK) == 1; 569 } 570 571 @Override 572 public Drawable newDrawable() { 573 return new AnimatedStateListDrawable(this, null); 574 } 575 576 @Override 577 public Drawable newDrawable(Resources res) { 578 return new AnimatedStateListDrawable(this, res); 579 } 580 581 private static long generateTransitionKey(int fromId, int toId) { 582 return (long) fromId << 32 | toId; 583 } 584 } 585 586 void setConstantState(@NonNull AnimatedStateListState state) { 587 super.setConstantState(state); 588 589 mState = state; 590 } 591 592 private AnimatedStateListDrawable(@Nullable AnimatedStateListState state, @Nullable Resources res) { 593 super(null); 594 595 final AnimatedStateListState newState = new AnimatedStateListState(state, this, res); 596 setConstantState(newState); 597 onStateChange(getState()); 598 jumpToCurrentState(); 599 } 600 601 /** 602 * Interpolates between frames with respect to their individual durations. 603 */ 604 private static class FrameInterpolator implements TimeInterpolator { 605 private int[] mFrameTimes; 606 private int mFrames; 607 private int mTotalDuration; 608 609 public FrameInterpolator(AnimationDrawable d, boolean reversed) { 610 updateFrames(d, reversed); 611 } 612 613 public int updateFrames(AnimationDrawable d, boolean reversed) { 614 final int N = d.getNumberOfFrames(); 615 mFrames = N; 616 617 if (mFrameTimes == null || mFrameTimes.length < N) { 618 mFrameTimes = new int[N]; 619 } 620 621 final int[] frameTimes = mFrameTimes; 622 int totalDuration = 0; 623 for (int i = 0; i < N; i++) { 624 final int duration = d.getDuration(reversed ? N - i - 1 : i); 625 frameTimes[i] = duration; 626 totalDuration += duration; 627 } 628 629 mTotalDuration = totalDuration; 630 return totalDuration; 631 } 632 633 public int getTotalDuration() { 634 return mTotalDuration; 635 } 636 637 @Override 638 public float getInterpolation(float input) { 639 final int elapsed = (int) (input * mTotalDuration + 0.5f); 640 final int N = mFrames; 641 final int[] frameTimes = mFrameTimes; 642 643 // Find the current frame and remaining time within that frame. 644 int remaining = elapsed; 645 int i = 0; 646 while (i < N && remaining >= frameTimes[i]) { 647 remaining -= frameTimes[i]; 648 i++; 649 } 650 651 // Remaining time is relative of total duration. 652 final float frameElapsed; 653 if (i < N) { 654 frameElapsed = remaining / (float) mTotalDuration; 655 } else { 656 frameElapsed = 0; 657 } 658 659 return i / (float) N + frameElapsed; 660 } 661 } 662} 663