/
SwipeDismissBehavior.java
460 lines (401 loc) · 16.1 KB
/
SwipeDismissBehavior.java
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
/*
* 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.google.android.material.behavior;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.VisibleForTesting;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.ViewCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat;
import androidx.core.view.accessibility.AccessibilityViewCommand;
import androidx.customview.widget.ViewDragHelper;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* An interaction behavior plugin for child views of {@link CoordinatorLayout} to provide support
* for the 'swipe-to-dismiss' gesture.
*/
public class SwipeDismissBehavior<V extends View> extends CoordinatorLayout.Behavior<V> {
/** A view is not currently being dragged or animating as a result of a fling/snap. */
public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE;
/**
* A view is currently being dragged. The position is currently changing as a result of user input
* or simulated user input.
*/
public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING;
/**
* A view is currently settling into place as a result of a fling or predefined non-interactive
* motion.
*/
public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef({SWIPE_DIRECTION_START_TO_END, SWIPE_DIRECTION_END_TO_START, SWIPE_DIRECTION_ANY})
@Retention(RetentionPolicy.SOURCE)
private @interface SwipeDirection {}
/**
* Swipe direction that only allows swiping in the direction of start-to-end. That is
* left-to-right in LTR, or right-to-left in RTL.
*/
public static final int SWIPE_DIRECTION_START_TO_END = 0;
/**
* Swipe direction that only allows swiping in the direction of end-to-start. That is
* right-to-left in LTR or left-to-right in RTL.
*/
public static final int SWIPE_DIRECTION_END_TO_START = 1;
/** Swipe direction which allows swiping in either direction. */
public static final int SWIPE_DIRECTION_ANY = 2;
private static final float DEFAULT_DRAG_DISMISS_THRESHOLD = 0.5f;
private static final float DEFAULT_ALPHA_START_DISTANCE = 0f;
private static final float DEFAULT_ALPHA_END_DISTANCE = DEFAULT_DRAG_DISMISS_THRESHOLD;
ViewDragHelper viewDragHelper;
OnDismissListener listener;
private boolean interceptingEvents;
private float sensitivity = 0f;
private boolean sensitivitySet;
int swipeDirection = SWIPE_DIRECTION_ANY;
float dragDismissThreshold = DEFAULT_DRAG_DISMISS_THRESHOLD;
float alphaStartSwipeDistance = DEFAULT_ALPHA_START_DISTANCE;
float alphaEndSwipeDistance = DEFAULT_ALPHA_END_DISTANCE;
/** Callback interface used to notify the application that the view has been dismissed. */
public interface OnDismissListener {
/** Called when {@code view} has been dismissed via swiping. */
public void onDismiss(View view);
/**
* Called when the drag state has changed.
*
* @param state the new state. One of {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link
* #STATE_SETTLING}.
*/
public void onDragStateChanged(int state);
}
/**
* Set the listener to be used when a dismiss event occurs.
*
* @param listener the listener to use.
*/
public void setListener(@Nullable OnDismissListener listener) {
this.listener = listener;
}
@VisibleForTesting
@Nullable
public OnDismissListener getListener() {
return listener;
}
/**
* Sets the swipe direction for this behavior.
*
* @param direction one of the {@link #SWIPE_DIRECTION_START_TO_END}, {@link
* #SWIPE_DIRECTION_END_TO_START} or {@link #SWIPE_DIRECTION_ANY}
*/
public void setSwipeDirection(@SwipeDirection int direction) {
swipeDirection = direction;
}
/**
* Set the threshold for telling if a view has been dragged enough to be dismissed.
*
* @param distance a ratio of a view's width, values are clamped to 0 >= x <= 1f;
*/
public void setDragDismissDistance(float distance) {
dragDismissThreshold = clamp(0f, distance, 1f);
}
/**
* The minimum swipe distance before the view's alpha is modified.
*
* @param fraction the distance as a fraction of the view's width.
*/
public void setStartAlphaSwipeDistance(float fraction) {
alphaStartSwipeDistance = clamp(0f, fraction, 1f);
}
/**
* The maximum swipe distance for the view's alpha is modified.
*
* @param fraction the distance as a fraction of the view's width.
*/
public void setEndAlphaSwipeDistance(float fraction) {
alphaEndSwipeDistance = clamp(0f, fraction, 1f);
}
/**
* Set the sensitivity used for detecting the start of a swipe. This only takes effect if no touch
* handling has occured yet.
*
* @param sensitivity Multiplier for how sensitive we should be about detecting the start of a
* drag. Larger values are more sensitive. 1.0f is normal.
*/
public void setSensitivity(float sensitivity) {
this.sensitivity = sensitivity;
sensitivitySet = true;
}
@Override
public boolean onLayoutChild(
@NonNull CoordinatorLayout parent, @NonNull V child, int layoutDirection) {
boolean handled = super.onLayoutChild(parent, child, layoutDirection);
if (ViewCompat.getImportantForAccessibility(child)
== ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
updateAccessibilityActions(child);
}
return handled;
}
@Override
public boolean onInterceptTouchEvent(
@NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) {
boolean dispatchEventToHelper = interceptingEvents;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
interceptingEvents =
parent.isPointInChildBounds(child, (int) event.getX(), (int) event.getY());
dispatchEventToHelper = interceptingEvents;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// Reset the ignore flag for next times
interceptingEvents = false;
break;
}
if (dispatchEventToHelper) {
ensureViewDragHelper(parent);
return viewDragHelper.shouldInterceptTouchEvent(event);
}
return false;
}
@Override
public boolean onTouchEvent(CoordinatorLayout parent, V child, MotionEvent event) {
if (viewDragHelper != null) {
viewDragHelper.processTouchEvent(event);
return true;
}
return false;
}
/**
* Called when the user's input indicates that they want to swipe the given view.
*
* @param view View the user is attempting to swipe
* @return true if the view can be dismissed via swiping, false otherwise
*/
public boolean canSwipeDismissView(@NonNull View view) {
return true;
}
private final ViewDragHelper.Callback dragCallback =
new ViewDragHelper.Callback() {
private static final int INVALID_POINTER_ID = -1;
private int originalCapturedViewLeft;
private int activePointerId = INVALID_POINTER_ID;
@Override
public boolean tryCaptureView(View child, int pointerId) {
// Only capture if we don't already have an active pointer id
return (activePointerId == INVALID_POINTER_ID || activePointerId == pointerId)
&& canSwipeDismissView(child);
}
@Override
public void onViewCaptured(@NonNull View capturedChild, int activePointerId) {
this.activePointerId = activePointerId;
originalCapturedViewLeft = capturedChild.getLeft();
// The view has been captured, and thus a drag is about to start so stop any parents
// intercepting
final ViewParent parent = capturedChild.getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
@Override
public void onViewDragStateChanged(int state) {
if (listener != null) {
listener.onDragStateChanged(state);
}
}
@Override
public void onViewReleased(@NonNull View child, float xVelocity, float yVelocity) {
// Reset the active pointer ID
activePointerId = INVALID_POINTER_ID;
final int childWidth = child.getWidth();
int targetLeft;
boolean dismiss = false;
if (shouldDismiss(child, xVelocity)) {
targetLeft =
xVelocity < 0f || child.getLeft() < originalCapturedViewLeft
? originalCapturedViewLeft - childWidth
: originalCapturedViewLeft + childWidth;
dismiss = true;
} else {
// Else, reset back to the original left
targetLeft = originalCapturedViewLeft;
}
if (viewDragHelper.settleCapturedViewAt(targetLeft, child.getTop())) {
ViewCompat.postOnAnimation(child, new SettleRunnable(child, dismiss));
} else if (dismiss && listener != null) {
listener.onDismiss(child);
}
}
private boolean shouldDismiss(@NonNull View child, float xVelocity) {
if (xVelocity != 0f) {
final boolean isRtl =
ViewCompat.getLayoutDirection(child) == ViewCompat.LAYOUT_DIRECTION_RTL;
if (swipeDirection == SWIPE_DIRECTION_ANY) {
// We don't care about the direction so return true
return true;
} else if (swipeDirection == SWIPE_DIRECTION_START_TO_END) {
// We only allow start-to-end swiping, so the fling needs to be in the
// correct direction
return isRtl ? xVelocity < 0f : xVelocity > 0f;
} else if (swipeDirection == SWIPE_DIRECTION_END_TO_START) {
// We only allow end-to-start swiping, so the fling needs to be in the
// correct direction
return isRtl ? xVelocity > 0f : xVelocity < 0f;
}
} else {
final int distance = child.getLeft() - originalCapturedViewLeft;
final int thresholdDistance = Math.round(child.getWidth() * dragDismissThreshold);
return Math.abs(distance) >= thresholdDistance;
}
return false;
}
@Override
public int getViewHorizontalDragRange(@NonNull View child) {
return child.getWidth();
}
@Override
public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
final boolean isRtl =
ViewCompat.getLayoutDirection(child) == ViewCompat.LAYOUT_DIRECTION_RTL;
int min;
int max;
if (swipeDirection == SWIPE_DIRECTION_START_TO_END) {
if (isRtl) {
min = originalCapturedViewLeft - child.getWidth();
max = originalCapturedViewLeft;
} else {
min = originalCapturedViewLeft;
max = originalCapturedViewLeft + child.getWidth();
}
} else if (swipeDirection == SWIPE_DIRECTION_END_TO_START) {
if (isRtl) {
min = originalCapturedViewLeft;
max = originalCapturedViewLeft + child.getWidth();
} else {
min = originalCapturedViewLeft - child.getWidth();
max = originalCapturedViewLeft;
}
} else {
min = originalCapturedViewLeft - child.getWidth();
max = originalCapturedViewLeft + child.getWidth();
}
return clamp(min, left, max);
}
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
return child.getTop();
}
@Override
public void onViewPositionChanged(@NonNull View child, int left, int top, int dx, int dy) {
final float startAlphaDistance =
originalCapturedViewLeft + child.getWidth() * alphaStartSwipeDistance;
final float endAlphaDistance =
originalCapturedViewLeft + child.getWidth() * alphaEndSwipeDistance;
if (left <= startAlphaDistance) {
child.setAlpha(1f);
} else if (left >= endAlphaDistance) {
child.setAlpha(0f);
} else {
// We're between the start and end distances
final float distance = fraction(startAlphaDistance, endAlphaDistance, left);
child.setAlpha(clamp(0f, 1f - distance, 1f));
}
}
};
private void ensureViewDragHelper(ViewGroup parent) {
if (viewDragHelper == null) {
viewDragHelper =
sensitivitySet
? ViewDragHelper.create(parent, sensitivity, dragCallback)
: ViewDragHelper.create(parent, dragCallback);
}
}
private class SettleRunnable implements Runnable {
private final View view;
private final boolean dismiss;
SettleRunnable(View view, boolean dismiss) {
this.view = view;
this.dismiss = dismiss;
}
@Override
public void run() {
if (viewDragHelper != null && viewDragHelper.continueSettling(true)) {
ViewCompat.postOnAnimation(view, this);
} else {
if (dismiss && listener != null) {
listener.onDismiss(view);
}
}
}
}
private void updateAccessibilityActions(View child) {
ViewCompat.removeAccessibilityAction(child, AccessibilityNodeInfoCompat.ACTION_DISMISS);
if (canSwipeDismissView(child)) {
ViewCompat.replaceAccessibilityAction(
child,
AccessibilityActionCompat.ACTION_DISMISS,
null,
new AccessibilityViewCommand() {
@Override
public boolean perform(@NonNull View view, @Nullable CommandArguments arguments) {
if (canSwipeDismissView(view)) {
final boolean isRtl =
ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_RTL;
boolean dismissToLeft =
(swipeDirection == SWIPE_DIRECTION_START_TO_END && isRtl)
|| (swipeDirection == SWIPE_DIRECTION_END_TO_START && !isRtl);
int offset = dismissToLeft ? -view.getWidth() : view.getWidth();
ViewCompat.offsetLeftAndRight(view, offset);
view.setAlpha(0f);
if (listener != null) {
listener.onDismiss(view);
}
return true;
}
return false;
}
});
}
}
static float clamp(float min, float value, float max) {
return Math.min(Math.max(min, value), max);
}
static int clamp(int min, int value, int max) {
return Math.min(Math.max(min, value), max);
}
/**
* Retrieve the current drag state of this behavior. This will return one of {@link #STATE_IDLE},
* {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}.
*
* @return The current drag state
*/
public int getDragState() {
return viewDragHelper != null ? viewDragHelper.getViewDragState() : STATE_IDLE;
}
/** The fraction that {@code value} is between {@code startValue} and {@code endValue}. */
static float fraction(float startValue, float endValue, float value) {
return (value - startValue) / (endValue - startValue);
}
}