summaryrefslogtreecommitdiffstats
path: root/src/com/android/messaging/ui/conversationlist/ConversationListSwipeHelper.java
blob: 498825915a3fb7d5b17a318ea389e8b1b4bd589f (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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
 * Copyright (C) 2015 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.messaging.ui.conversationlist;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.content.Context;
import android.content.res.Resources;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnItemTouchListener;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;

import com.android.messaging.R;
import com.android.messaging.util.Assert;
import com.android.messaging.util.UiUtils;

/**
 * Animation and touch helper class for Conversation List swipe.
 */
public class ConversationListSwipeHelper implements OnItemTouchListener {
    private static final int UNIT_SECONDS = 1000;
    private static final boolean ANIMATING = true;

    private static final float ERROR_FACTOR_MULTIPLIER = 1.2f;
    private static final float PERCENTAGE_OF_WIDTH_TO_DISMISS = 0.4f;
    private static final float FLING_PERCENTAGE_OF_WIDTH_TO_DISMISS = 0.05f;

    private static final int SWIPE_DIRECTION_NONE = 0;
    private static final int SWIPE_DIRECTION_LEFT = 1;
    private static final int SWIPE_DIRECTION_RIGHT = 2;

    private final RecyclerView mRecyclerView;
    private final long mDefaultRestoreAnimationDuration;
    private final long mDefaultDismissAnimationDuration;
    private final long mMaxTranslationAnimationDuration;
    private final int mTouchSlop;
    private final int mMinimumFlingVelocity;
    private final int mMaximumFlingVelocity;

    /* Valid throughout a single gesture. */
    private VelocityTracker mVelocityTracker;
    private float mInitialX;
    private float mInitialY;
    private boolean mIsSwiping;
    private ConversationListItemView mListItemView;

    public ConversationListSwipeHelper(final RecyclerView recyclerView) {
        mRecyclerView = recyclerView;

        final Context context = mRecyclerView.getContext();
        final Resources res = context.getResources();
        mDefaultRestoreAnimationDuration = res.getInteger(R.integer.swipe_duration_ms);
        mDefaultDismissAnimationDuration = res.getInteger(R.integer.swipe_duration_ms);
        mMaxTranslationAnimationDuration = res.getInteger(R.integer.swipe_duration_ms);

        final ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
        mTouchSlop = viewConfiguration.getScaledPagingTouchSlop();
        mMaximumFlingVelocity = Math.min(
                viewConfiguration.getScaledMaximumFlingVelocity(),
                res.getInteger(R.integer.swipe_max_fling_velocity_px_per_s));
        mMinimumFlingVelocity = viewConfiguration.getScaledMinimumFlingVelocity();
    }

    @Override
    public boolean onInterceptTouchEvent(final RecyclerView recyclerView, final MotionEvent event) {
        if (event.getPointerCount() > 1) {
            // Ignore subsequent pointers.
            return false;
        }

        // We are not yet tracking a swipe gesture. Begin detection by spying on
        // touch events bubbling down to our children.
        final int action = event.getActionMasked();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                if (!hasGestureSwipeTarget()) {
                    onGestureStart();

                    mVelocityTracker.addMovement(event);
                    mInitialX = event.getX();
                    mInitialY = event.getY();

                    final View viewAtPoint = mRecyclerView.findChildViewUnder(mInitialX, mInitialY);
                    final ConversationListItemView child = (ConversationListItemView) viewAtPoint;
                    if (viewAtPoint instanceof ConversationListItemView &&
                            child != null && child.isSwipeAnimatable()) {
                        // Begin detecting swipe on the target for the rest of the gesture.
                        mListItemView = child;
                        if (mListItemView.isAnimating()) {
                            mListItemView = null;
                        }
                    } else {
                        mListItemView = null;
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (hasValidGestureSwipeTarget()) {
                    mVelocityTracker.addMovement(event);

                    final int historicalCount = event.getHistorySize();
                    // First consume the historical events, then consume the current ones.
                    for (int i = 0; i < historicalCount + 1; i++) {
                        float currX;
                        float currY;
                        if (i < historicalCount) {
                            currX = event.getHistoricalX(i);
                            currY = event.getHistoricalY(i);
                        } else {
                            currX = event.getX();
                            currY = event.getY();
                        }
                        final float deltaX = currX - mInitialX;
                        final float deltaY = currY - mInitialY;
                        final float absDeltaX = Math.abs(deltaX);
                        final float absDeltaY = Math.abs(deltaY);

                        if (!mIsSwiping && absDeltaY > mTouchSlop
                                && absDeltaY > (ERROR_FACTOR_MULTIPLIER * absDeltaX)) {
                            // Stop detecting swipe for the remainder of this gesture.
                            onGestureEnd();
                            return false;
                        }

                        if (absDeltaX > mTouchSlop) {
                            // Swipe detected. Return true so we can handle the gesture in
                            // onTouchEvent.
                            mIsSwiping = true;

                            // We don't want to suddenly jump the slop distance.
                            mInitialX = event.getX();
                            mInitialY = event.getY();

                            onSwipeGestureStart(mListItemView);
                            return true;
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (hasGestureSwipeTarget()) {
                    onGestureEnd();
                }
                break;
        }

        // Start intercepting touch events from children if we detect a swipe.
        return mIsSwiping;
    }

    @Override
    public void onTouchEvent(final RecyclerView recyclerView, final MotionEvent event) {
        // We should only be here if we intercepted the touch due to swipe.
        Assert.isTrue(mIsSwiping);

        // We are now tracking a swipe gesture.
        mVelocityTracker.addMovement(event);

        final int action = event.getActionMasked();
        switch (action) {
            case MotionEvent.ACTION_OUTSIDE:
            case MotionEvent.ACTION_MOVE:
                if (hasValidGestureSwipeTarget()) {
                    mListItemView.setSwipeTranslationX(event.getX() - mInitialX);
                }
                break;
            case MotionEvent.ACTION_UP:
                if (hasValidGestureSwipeTarget()) {
                    final float maxVelocity = mMaximumFlingVelocity;
                    mVelocityTracker.computeCurrentVelocity(UNIT_SECONDS, maxVelocity);
                    final float velocityX = getLastComputedXVelocity();

                    final float translationX = mListItemView.getSwipeTranslationX();

                    int swipeDirection = SWIPE_DIRECTION_NONE;
                    if (translationX != 0) {
                        swipeDirection =
                                translationX > 0 ? SWIPE_DIRECTION_RIGHT : SWIPE_DIRECTION_LEFT;
                    } else if (velocityX != 0) {
                        swipeDirection =
                                velocityX > 0 ? SWIPE_DIRECTION_RIGHT : SWIPE_DIRECTION_LEFT;
                    }

                    final boolean fastEnough = isTargetSwipedFastEnough();
                    final boolean farEnough = isTargetSwipedFarEnough();

                    final boolean shouldDismiss =  (fastEnough || farEnough);

                    if (shouldDismiss) {
                        if (fastEnough) {
                            animateDismiss(mListItemView, velocityX);
                        } else {
                            animateDismiss(mListItemView, swipeDirection);
                        }
                    } else {
                        animateRestore(mListItemView, velocityX);
                    }

                    onSwipeGestureEnd(mListItemView,
                            shouldDismiss ? swipeDirection : SWIPE_DIRECTION_NONE);
                } else {
                    onGestureEnd();
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                if (hasValidGestureSwipeTarget()) {
                    animateRestore(mListItemView, 0f);
                    onSwipeGestureEnd(mListItemView, SWIPE_DIRECTION_NONE);
                } else {
                    onGestureEnd();
                }
                break;
        }
    }


    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    }

    /**
     * We have started to intercept a series of touch events.
     */
    private void onGestureStart() {
        mIsSwiping = false;
        // Work around bug in RecyclerView that sends two identical ACTION_DOWN
        // events to #onInterceptTouchEvent.
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.clear();
    }

    /**
     * The series of touch events has been detected as a swipe.
     *
     * Now that the gesture is a swipe, we will begin translating the view of the
     * given viewHolder.
     */
    private void onSwipeGestureStart(final ConversationListItemView itemView) {
        mRecyclerView.getParent().requestDisallowInterceptTouchEvent(true);
        setHardwareAnimatingLayerType(itemView, ANIMATING);
        itemView.setAnimating(true);
    }

    /**
     * The current swipe gesture is complete.
     */
    private void onSwipeGestureEnd(final ConversationListItemView itemView,
            final int swipeDirection) {
        if (swipeDirection == SWIPE_DIRECTION_RIGHT || swipeDirection == SWIPE_DIRECTION_LEFT) {
            itemView.onSwipeComplete();
        }

        // Balances out onSwipeGestureStart.
        itemView.setAnimating(false);

        onGestureEnd();
    }

    /**
     * The series of touch events has ended in an {@link MotionEvent#ACTION_UP}
     * or {@link MotionEvent#ACTION_CANCEL}.
     */
    private void onGestureEnd() {
        mVelocityTracker.recycle();
        mVelocityTracker = null;
        mIsSwiping = false;
        mListItemView = null;
    }

    /**
     * A swipe animation has started.
     */
    private void onSwipeAnimationStart(final ConversationListItemView itemView) {
        // Disallow interactions.
        itemView.setAnimating(true);
        ViewCompat.setHasTransientState(itemView, true);
        setHardwareAnimatingLayerType(itemView, ANIMATING);
    }

    /**
     * The swipe animation has ended.
     */
    private void onSwipeAnimationEnd(final ConversationListItemView itemView) {
        // Restore interactions.
        itemView.setAnimating(false);
        ViewCompat.setHasTransientState(itemView, false);
        setHardwareAnimatingLayerType(itemView, !ANIMATING);
    }

    /**
     * Animate the dismissal of the given item. The given velocityX is taken into consideration for
     * the animation duration. Whether the item is dismissed to the left or right is dependent on
     * the given velocityX.
     */
    private void animateDismiss(final ConversationListItemView itemView, final float velocityX) {
        Assert.isTrue(velocityX != 0);
        final int direction = velocityX > 0 ? SWIPE_DIRECTION_RIGHT : SWIPE_DIRECTION_LEFT;
        animateDismiss(itemView, direction, velocityX);
    }

    /**
     * Animate the dismissal of the given item. The velocityX is assumed to be 0.
     */
    private void animateDismiss(final ConversationListItemView itemView, final int swipeDirection) {
        animateDismiss(itemView, swipeDirection, 0f);
    }

    /**
     * Animate the dismissal of the given item.
     */
    private void animateDismiss(final ConversationListItemView itemView,
            final int swipeDirection, final float velocityX) {
        Assert.isTrue(swipeDirection != SWIPE_DIRECTION_NONE);

        onSwipeAnimationStart(itemView);

        final float animateTo = (swipeDirection == SWIPE_DIRECTION_RIGHT) ?
                mRecyclerView.getWidth() : -mRecyclerView.getWidth();
        final long duration;
        if (velocityX != 0) {
            final float deltaX = animateTo - itemView.getSwipeTranslationX();
            duration = calculateTranslationDuration(deltaX, velocityX);
        } else {
            duration = mDefaultDismissAnimationDuration;
        }

        final ObjectAnimator animator = getSwipeTranslationXAnimator(
                itemView, animateTo, duration, UiUtils.DEFAULT_INTERPOLATOR);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(final Animator animation) {
                onSwipeAnimationEnd(itemView);
            }
        });
        animator.start();
    }

    /**
     * Animate the bounce back of the given item.
     */
    private void animateRestore(final ConversationListItemView itemView,
            final float velocityX) {
        onSwipeAnimationStart(itemView);

        final float translationX = itemView.getSwipeTranslationX();
        final long duration;
        if (velocityX != 0 // Has velocity.
                && velocityX > 0 != translationX > 0) { // Right direction.
            duration = calculateTranslationDuration(translationX, velocityX);
        } else {
            duration = mDefaultRestoreAnimationDuration;
        }
        final ObjectAnimator animator = getSwipeTranslationXAnimator(
                itemView, 0f, duration, UiUtils.DEFAULT_INTERPOLATOR);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(final Animator animation) {
                       onSwipeAnimationEnd(itemView);
            }
        });
        animator.start();
    }

    /**
     * Create and start an animator that animates the given view's translationX
     * from its current value to the value given by animateTo.
     */
    private ObjectAnimator getSwipeTranslationXAnimator(final ConversationListItemView itemView,
            final float animateTo, final long duration, final TimeInterpolator interpolator) {
        final ObjectAnimator animator =
                ObjectAnimator.ofFloat(itemView, "swipeTranslationX", animateTo);
        animator.setDuration(duration);
        animator.setInterpolator(interpolator);
        return animator;
    }

    /**
     * Determine if the swipe has enough velocity to be dismissed.
     */
    private boolean isTargetSwipedFastEnough() {
        final float velocityX = getLastComputedXVelocity();
        final float velocityY = mVelocityTracker.getYVelocity();
        final float minVelocity = mMinimumFlingVelocity;
        final float translationX = mListItemView.getSwipeTranslationX();
        final float width = mListItemView.getWidth();
        return (Math.abs(velocityX) > minVelocity) // Fast enough.
                && (Math.abs(velocityX) > Math.abs(velocityY)) // Not unintentional.
                && (velocityX > 0) == (translationX > 0) // Right direction.
                && Math.abs(translationX) >
                    FLING_PERCENTAGE_OF_WIDTH_TO_DISMISS * width; // Enough movement.
  }

    /**
     * Only used during a swipe gesture. Determine if the swipe has enough distance to be
     * dismissed.
     */
    private boolean isTargetSwipedFarEnough() {
        final float velocityX = getLastComputedXVelocity();

        final float translationX = mListItemView.getSwipeTranslationX();
        final float width = mListItemView.getWidth();

        return (velocityX >= 0) == (translationX > 0) // Right direction.
                && Math.abs(translationX) >
                    PERCENTAGE_OF_WIDTH_TO_DISMISS * width; // Enough movement.
  }

    private long calculateTranslationDuration(final float deltaPosition, final float velocity) {
        Assert.isTrue(velocity != 0);
        final float durationInSeconds = Math.abs(deltaPosition / velocity);
        return Math.min((int) (durationInSeconds * UNIT_SECONDS), mMaxTranslationAnimationDuration);
    }

    private boolean hasGestureSwipeTarget() {
        return mListItemView != null;
    }

    private boolean hasValidGestureSwipeTarget() {
        return hasGestureSwipeTarget() && mListItemView.getParent() == mRecyclerView;
    }

    /**
     * Enable a hardware layer for the it view and build that layer.
     */
    private void setHardwareAnimatingLayerType(final ConversationListItemView itemView,
            final boolean animating) {
        if (animating) {
            itemView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            if (itemView.getWindowToken() != null) {
                itemView.buildLayer();
            }
        } else {
            itemView.setLayerType(View.LAYER_TYPE_NONE, null);
        }
    }

    private float getLastComputedXVelocity() {
        return mVelocityTracker.getXVelocity();
    }
}