summaryrefslogtreecommitdiffstats
path: root/src/com/android/launcher3/anim/SpringAnimationHandler.java
blob: 3e58adc3fabac22ec73d8629e246b8b04922be82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.launcher3.anim;

import android.support.animation.FloatPropertyCompat;
import android.support.animation.SpringAnimation;
import android.support.animation.SpringForce;
import android.support.annotation.IntDef;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;

import com.android.launcher3.R;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;

/**
 * Handler class that manages springs for a set of views that should all move based on the same
 * {@link MotionEvent}s.
 *
 * Supports setting either X or Y velocity on the list of springs added to this handler.
 */
public class SpringAnimationHandler<T> {

    private static final String TAG = "SpringAnimationHandler";
    private static final boolean DEBUG = false;

    private static final float VELOCITY_DAMPING_FACTOR = 0.175f;

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({Y_DIRECTION, X_DIRECTION})
    public @interface Direction {}
    public static final int Y_DIRECTION = 0;
    public static final int X_DIRECTION = 1;
    private int mVelocityDirection;

    private VelocityTracker mVelocityTracker;
    private float mCurrentVelocity = 0;
    private boolean mShouldComputeVelocity = false;

    private AnimationFactory<T> mAnimationFactory;

    private ArrayList<SpringAnimation> mAnimations = new ArrayList<>();

    /**
     * @param direction Either {@link #X_DIRECTION} or {@link #Y_DIRECTION}.
     *                  Determines which direction we use to calculate and set the velocity.
     * @param factory   The AnimationFactory is responsible for initializing and updating the
     *                  SpringAnimations added to this class.
     */
    public SpringAnimationHandler(@Direction int direction, AnimationFactory<T> factory) {
        mVelocityDirection = direction;
        mAnimationFactory = factory;
    }

    /**
     * Adds a new or recycled animation to the list of springs handled by this class.
     *
     * @param view The view the spring is attached to.
     * @param object Used to initialize and update the spring.
     */
    public void add(View view, T object) {
        SpringAnimation spring = (SpringAnimation) view.getTag(R.id.spring_animation_tag);
        if (spring == null) {
            spring = mAnimationFactory.initialize(object);
            view.setTag(R.id.spring_animation_tag, spring);
        }
        mAnimationFactory.update(spring, object);
        spring.setStartVelocity(mCurrentVelocity);
        mAnimations.add(spring);
    }

    /**
     * Stops and removes the spring attached to {@param view}.
     */
    public void remove(View view) {
        SpringAnimation animation = (SpringAnimation) view.getTag(R.id.spring_animation_tag);
        if (animation.canSkipToEnd()) {
            animation.skipToEnd();
        }
        mAnimations.remove(animation);
    }

    public void addMovement(MotionEvent event) {
        int action = event.getActionMasked();
        if (DEBUG) Log.d(TAG, "addMovement#action=" + action);
        switch (action) {
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_DOWN:
                reset();
                break;
        }

        getVelocityTracker().addMovement(event);
        mShouldComputeVelocity = true;
    }

    public void animateToFinalPosition(float position, int startValue) {
        animateToFinalPosition(position, startValue, mShouldComputeVelocity);
    }

    /**
     * @param position The final animation position.
     * @param startValue < 0 if scrolling from start to end; > 0 if scrolling from end to start
     *                   The magnitude of the number changes how the spring will move.
     * @param setVelocity If true, we set the velocity to {@link #mCurrentVelocity} before
     *                    starting the animation.
     */
    private void animateToFinalPosition(float position, int startValue, boolean setVelocity) {
        if (DEBUG) {
            Log.d(TAG, "animateToFinalPosition#position=" + position + ", startValue=" + startValue);
        }

        if (mShouldComputeVelocity) {
            mCurrentVelocity = computeVelocity();
        }

        int size = mAnimations.size();
        for (int i = 0; i < size; ++i) {
            mAnimations.get(i).setStartValue(startValue);
            if (setVelocity) {
                mAnimations.get(i).setStartVelocity(mCurrentVelocity);
            }
            mAnimations.get(i).animateToFinalPosition(position);
        }

        reset();
    }

    /**
     * Similar to {@link #animateToFinalPosition(float, int)}, but used in cases where we want to
     * manually set the velocity.
     */
    public void animateToPositionWithVelocity(float position, int startValue, float velocity) {
        if (DEBUG) {
            Log.d(TAG, "animateToPosition#pos=" + position + ", start=" + startValue
                    + ", velocity=" + velocity);
        }

        mCurrentVelocity = velocity;
        mShouldComputeVelocity = false;
        animateToFinalPosition(position, startValue, true);
    }


    public boolean isRunning() {
        // All the animations run at the same time so we can just check the first one.
        return !mAnimations.isEmpty() && mAnimations.get(0).isRunning();
    }

    public void skipToEnd() {
        if (DEBUG) Log.d(TAG, "setStartVelocity#skipToEnd");
        if (DEBUG) Log.v(TAG, "setStartVelocity#skipToEnd", new Exception());

        int size = mAnimations.size();
        for (int i = 0; i < size; ++i) {
            if (mAnimations.get(i).canSkipToEnd()) {
                mAnimations.get(i).skipToEnd();
            }
        }
    }

    public void reset() {
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
        mCurrentVelocity = 0;
        mShouldComputeVelocity = false;
    }


    private float computeVelocity() {
        getVelocityTracker().computeCurrentVelocity(1000 /* millis */);

        float velocity = isVerticalDirection()
                ? getVelocityTracker().getYVelocity()
                : getVelocityTracker().getXVelocity();
        velocity *= VELOCITY_DAMPING_FACTOR;

        if (DEBUG) Log.d(TAG, "computeVelocity=" + velocity);
        return velocity;
    }

    private boolean isVerticalDirection() {
        return mVelocityDirection == Y_DIRECTION;
    }

    private VelocityTracker getVelocityTracker() {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        return mVelocityTracker;
    }

    /**
     * This interface is used to initialize and update the SpringAnimations added to the
     * {@link SpringAnimationHandler}.
     *
     * @param <T> The object that each SpringAnimation is attached to.
     */
    public interface AnimationFactory<T> {

        /**
         * Initializes a new Spring for {@param object}.
         */
        SpringAnimation initialize(T object);

        /**
         * Updates the value of {@param spring} based on {@param object}.
         */
        void update(SpringAnimation spring, T object);
    }

    /**
     * Helper method to create a new SpringAnimation for {@param view}.
     */
    public static SpringAnimation forView(View view, FloatPropertyCompat property, float finalPos) {
        SpringAnimation spring = new SpringAnimation(view, property, finalPos);
        spring.setSpring(new SpringForce(finalPos));
        return spring;
    }

}