1/* 2 * Copyright (C) 2015 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.support.design.widget; 18 19import android.util.StateSet; 20 21import java.util.ArrayList; 22 23final class StateListAnimator { 24 25 private final ArrayList<Tuple> mTuples = new ArrayList<>(); 26 27 private Tuple mLastMatch = null; 28 ValueAnimatorCompat mRunningAnimator = null; 29 30 private final ValueAnimatorCompat.AnimatorListener mAnimationListener 31 = new ValueAnimatorCompat.AnimatorListenerAdapter() { 32 @Override 33 public void onAnimationEnd(ValueAnimatorCompat animator) { 34 if (mRunningAnimator == animator) { 35 mRunningAnimator = null; 36 } 37 } 38 }; 39 40 /** 41 * Associates the given Animation with the provided drawable state specs so that it will be run 42 * when the View's drawable state matches the specs. 43 * 44 * @param specs The drawable state specs to match against 45 * @param animator The animator to run when the specs match 46 */ 47 public void addState(int[] specs, ValueAnimatorCompat animator) { 48 Tuple tuple = new Tuple(specs, animator); 49 animator.addListener(mAnimationListener); 50 mTuples.add(tuple); 51 } 52 53 /** 54 * Called by View 55 */ 56 void setState(int[] state) { 57 Tuple match = null; 58 final int count = mTuples.size(); 59 for (int i = 0; i < count; i++) { 60 final Tuple tuple = mTuples.get(i); 61 if (StateSet.stateSetMatches(tuple.mSpecs, state)) { 62 match = tuple; 63 break; 64 } 65 } 66 if (match == mLastMatch) { 67 return; 68 } 69 if (mLastMatch != null) { 70 cancel(); 71 } 72 73 mLastMatch = match; 74 75 if (match != null) { 76 start(match); 77 } 78 } 79 80 private void start(Tuple match) { 81 mRunningAnimator = match.mAnimator; 82 mRunningAnimator.start(); 83 } 84 85 private void cancel() { 86 if (mRunningAnimator != null) { 87 mRunningAnimator.cancel(); 88 mRunningAnimator = null; 89 } 90 } 91 92 /** 93 * If there is an animation running for a recent state change, ends it. 94 * 95 * <p>This causes the animation to assign the end value(s) to the View.</p> 96 */ 97 public void jumpToCurrentState() { 98 if (mRunningAnimator != null) { 99 mRunningAnimator.end(); 100 mRunningAnimator = null; 101 } 102 } 103 104 static class Tuple { 105 final int[] mSpecs; 106 final ValueAnimatorCompat mAnimator; 107 108 Tuple(int[] specs, ValueAnimatorCompat animator) { 109 mSpecs = specs; 110 mAnimator = animator; 111 } 112 } 113}