-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathTopSheetBehavior.java
661 lines (588 loc) · 24 KB
/
TopSheetBehavior.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.NestedScrollingChild;
import androidx.core.view.ViewCompat;
import androidx.customview.view.AbsSavedState;
import androidx.customview.widget.ViewDragHelper;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
/**
* An interaction behavior plugin for a child view of {@link CoordinatorLayout} to make it work as
* a bottom sheet.
*/
public class TopSheetBehavior<V extends View> extends CoordinatorLayout.Behavior<V> {
/**
* Callback for monitoring events about bottom sheets.
*/
public abstract static class TopSheetCallback {
/**
* Called when the bottom sheet changes its state.
*
* @param bottomSheet The bottom sheet view.
* @param newState The new state. This will be one of {@link #STATE_DRAGGING},
* {@link #STATE_SETTLING}, {@link #STATE_EXPANDED},
* {@link #STATE_COLLAPSED}, or {@link #STATE_HIDDEN}.
*/
public abstract void onStateChanged(@NonNull View bottomSheet, @State int newState);
/**
* Called when the bottom sheet is being dragged.
*
* @param bottomSheet The bottom sheet view.
* @param slideOffset The new offset of this bottom sheet within its range, from 0 to 1
* when it is moving upward, and from 0 to -1 when it moving downward.
*/
public abstract void onSlide(@NonNull View bottomSheet, float slideOffset);
}
public static final int STATE_DRAGGING = 1;
public static final int STATE_SETTLING = 2;
public static final int STATE_EXPANDED = 3;
public static final int STATE_COLLAPSED = 4;
public static final int STATE_HIDDEN = 5;
@IntDef({STATE_EXPANDED, STATE_COLLAPSED, STATE_DRAGGING, STATE_SETTLING, STATE_HIDDEN})
@Retention(RetentionPolicy.SOURCE)
public @interface State {
}
private static final float HIDE_THRESHOLD = 0.5f;
private static final float HIDE_FRICTION = 0.1f;
private final float mMaximumVelocity;
private int mPeekHeight;
private int mMinOffset;
private int mMaxOffset;
private boolean mHideable;
private boolean mSkipCollapsed;
@State
private int mState = STATE_COLLAPSED;
private ViewDragHelper mViewDragHelper;
private boolean mIgnoreEvents;
private int mLastNestedScrollDy;
private boolean mNestedScrolled;
private WeakReference<V> mViewRef;
private WeakReference<View> mNestedScrollingChildRef;
private TopSheetCallback mCallback;
private VelocityTracker mVelocityTracker;
private int mActivePointerId;
private int mInitialY;
private boolean mTouchingScrollingChild;
public TopSheetBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
com.google.android.material.R.styleable.BottomSheetBehavior_Layout);
setPeekHeight(a.getDimensionPixelSize(
com.google.android.material.R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight, 0));
setHideable(a.getBoolean(com.google.android.material.R.styleable.BottomSheetBehavior_Layout_behavior_hideable, false));
setSkipCollapsed(a.getBoolean(com.google.android.material.R.styleable.BottomSheetBehavior_Layout_behavior_skipCollapsed,
false));
a.recycle();
ViewConfiguration configuration = ViewConfiguration.get(context);
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
}
@Override
public Parcelable onSaveInstanceState(@NonNull CoordinatorLayout parent, @NonNull V child) {
return new SavedState(super.onSaveInstanceState(parent, child), mState);
}
@Override
public void onRestoreInstanceState(@NonNull CoordinatorLayout parent, @NonNull V child, @NonNull Parcelable state) {
SavedState ss = (SavedState) state;
assert ss.getSuperState() != null;
super.onRestoreInstanceState(parent, child, ss.getSuperState());
// Intermediate states are restored as collapsed state
if (ss.state == STATE_DRAGGING || ss.state == STATE_SETTLING) {
mState = STATE_COLLAPSED;
} else {
mState = ss.state;
}
}
@Override
public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull V child, int layoutDirection) {
if (ViewCompat.getFitsSystemWindows(parent) && !ViewCompat.getFitsSystemWindows(child)) {
child.setFitsSystemWindows(true);
}
int savedTop = child.getTop();
// First let the parent lay it out
parent.onLayoutChild(child, layoutDirection);
// Offset the bottom sheet
mMinOffset = Math.max(-child.getHeight(), -(child.getHeight() - mPeekHeight));
mMaxOffset = 0;
if (mState == STATE_EXPANDED) {
ViewCompat.offsetTopAndBottom(child, mMaxOffset);
} else if (mHideable && mState == STATE_HIDDEN) {
ViewCompat.offsetTopAndBottom(child, -child.getHeight());
} else if (mState == STATE_COLLAPSED) {
ViewCompat.offsetTopAndBottom(child, mMinOffset);
} else if (mState == STATE_DRAGGING || mState == STATE_SETTLING) {
ViewCompat.offsetTopAndBottom(child, savedTop - child.getTop());
}
if (mViewDragHelper == null) {
mViewDragHelper = ViewDragHelper.create(parent, mDragCallback);
}
mViewRef = new WeakReference<>(child);
mNestedScrollingChildRef = new WeakReference<>(findScrollingChild(child));
return true;
}
@Override
public boolean onInterceptTouchEvent(@NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) {
if (!child.isShown()) {
return false;
}
int action = event.getActionMasked();
// Record the velocity
if (action == MotionEvent.ACTION_DOWN) {
reset();
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
switch (action) {
case MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
mTouchingScrollingChild = false;
mActivePointerId = MotionEvent.INVALID_POINTER_ID;
// Reset the ignore flag
if (mIgnoreEvents) {
mIgnoreEvents = false;
return false;
}
}
case MotionEvent.ACTION_DOWN -> {
int initialX = (int) event.getX();
mInitialY = (int) event.getY();
View scroll = mNestedScrollingChildRef.get();
if (scroll != null && parent.isPointInChildBounds(scroll, initialX, mInitialY)) {
mActivePointerId = event.getPointerId(event.getActionIndex());
mTouchingScrollingChild = true;
}
mIgnoreEvents = mActivePointerId == MotionEvent.INVALID_POINTER_ID &&
!parent.isPointInChildBounds(child, initialX, mInitialY);
}
}
if (!mIgnoreEvents && mViewDragHelper.shouldInterceptTouchEvent(event)) {
return true;
}
// We have to handle cases that the ViewDragHelper does not capture the bottom sheet because
// it is not the top most view of its parent. This is not necessary when the touch event is
// happening over the scrolling content as nested scrolling logic handles that case.
View scroll = mNestedScrollingChildRef.get();
return action == MotionEvent.ACTION_MOVE && scroll != null &&
!mIgnoreEvents && mState != STATE_DRAGGING &&
!parent.isPointInChildBounds(scroll, (int) event.getX(), (int) event.getY()) &&
Math.abs(mInitialY - event.getY()) > mViewDragHelper.getTouchSlop();
}
@Override
public boolean onTouchEvent(@NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) {
if (!child.isShown()) {
return false;
}
int action = event.getActionMasked();
if (mState == STATE_DRAGGING && action == MotionEvent.ACTION_DOWN) {
return true;
}
if (mViewDragHelper != null) {
//no crash
mViewDragHelper.processTouchEvent(event);
// Record the velocity
if (action == MotionEvent.ACTION_DOWN) {
reset();
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
// The ViewDragHelper tries to capture only the top-most View. We have to explicitly tell it
// to capture the bottom sheet in case it is not captured and the touch slop is passed.
if (action == MotionEvent.ACTION_MOVE && !mIgnoreEvents) {
if (Math.abs(mInitialY - event.getY()) > mViewDragHelper.getTouchSlop()) {
mViewDragHelper.captureChildView(child, event.getPointerId(event.getActionIndex()));
}
}
}
return !mIgnoreEvents;
}
@Override
public boolean onStartNestedScroll(
@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View directTargetChild,
@NonNull View target, int nestedScrollAxes, @ViewCompat.NestedScrollType int type
) {
mLastNestedScrollDy = 0;
mNestedScrolled = false;
return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
}
@Override
public void onNestedPreScroll(
@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target,
int dx, int dy, @NonNull int[] consumed, @ViewCompat.NestedScrollType int type
) {
View scrollingChild = mNestedScrollingChildRef.get();
if (target != scrollingChild) {
return;
}
int currentTop = child.getTop();
int newTop = currentTop - dy;
if (dy > 0) { // Upward
if (!target.canScrollVertically(1)) {
if (newTop >= mMinOffset || mHideable) {
consumed[1] = dy;
ViewCompat.offsetTopAndBottom(child, -dy);
setStateInternal(STATE_DRAGGING);
} else {
consumed[1] = currentTop - mMinOffset;
ViewCompat.offsetTopAndBottom(child, -consumed[1]);
setStateInternal(STATE_COLLAPSED);
}
}
} else if (dy < 0) { // Downward
// Negative to check scrolling up, positive to check scrolling down
if (newTop < mMaxOffset) {
consumed[1] = dy;
ViewCompat.offsetTopAndBottom(child, -dy);
setStateInternal(STATE_DRAGGING);
} else {
consumed[1] = currentTop - mMaxOffset;
ViewCompat.offsetTopAndBottom(child, -consumed[1]);
setStateInternal(STATE_EXPANDED);
}
}
dispatchOnSlide(child.getTop());
mLastNestedScrollDy = dy;
mNestedScrolled = true;
}
@Override
public void onStopNestedScroll(
@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target,
@ViewCompat.NestedScrollType int type
) {
if (child.getTop() == mMaxOffset) {
setStateInternal(STATE_EXPANDED);
return;
}
if (target != mNestedScrollingChildRef.get() || !mNestedScrolled) {
return;
}
int top;
int targetState;
if (mLastNestedScrollDy < 0) {
top = mMaxOffset;
targetState = STATE_EXPANDED;
} else if (mHideable && shouldHide(child, getYVelocity())) {
top = -child.getHeight();
targetState = STATE_HIDDEN;
} else if (mLastNestedScrollDy == 0) {
int currentTop = child.getTop();
if (Math.abs(currentTop - mMinOffset) > Math.abs(currentTop - mMaxOffset)) {
top = mMaxOffset;
targetState = STATE_EXPANDED;
} else {
top = mMinOffset;
targetState = STATE_COLLAPSED;
}
} else {
top = mMinOffset;
targetState = STATE_COLLAPSED;
}
if (mViewDragHelper.smoothSlideViewTo(child, child.getLeft(), top)) {
setStateInternal(STATE_SETTLING);
ViewCompat.postOnAnimation(child, new SettleRunnable(child, targetState));
} else {
setStateInternal(targetState);
}
mNestedScrolled = false;
}
@Override
public boolean onNestedPreFling(@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target,
float velocityX, float velocityY) {
return target == mNestedScrollingChildRef.get() &&
(mState != STATE_EXPANDED ||
super.onNestedPreFling(coordinatorLayout, child, target,
velocityX, velocityY));
}
/**
* Sets the height of the bottom sheet when it is collapsed.
*
* @param peekHeight The height of the collapsed bottom sheet in pixels.
*/
public final void setPeekHeight(int peekHeight) {
mPeekHeight = Math.max(0, peekHeight);
if (mViewRef != null && mViewRef.get() != null) {
mMinOffset = Math.max(-mViewRef.get().getHeight(), -(mViewRef.get().getHeight() - mPeekHeight));
}
}
public void setHideable(boolean hideable) {
mHideable = hideable;
}
public void setSkipCollapsed(boolean skipCollapsed) {
mSkipCollapsed = skipCollapsed;
}
public boolean getSkipCollapsed() {
return mSkipCollapsed;
}
/**
* Sets a callback to be notified of bottom sheet events.
*
* @param callback The callback to notify when bottom sheet events occur.
*/
public void setTopSheetCallback(TopSheetCallback callback) {
mCallback = callback;
}
/**
* Sets the state of the bottom sheet. The bottom sheet will transition to that state with
* animation.
*
* @param state One of {@link #STATE_COLLAPSED}, {@link #STATE_EXPANDED}, or
* {@link #STATE_HIDDEN}.
*/
public final void setState(@State int state) {
if (state == mState) {
return;
}
if (mViewRef == null) {
// The view is not laid out yet; modify mState and let onLayoutChild handle it later
if (state == STATE_COLLAPSED || state == STATE_EXPANDED ||
(mHideable && state == STATE_HIDDEN)) {
mState = state;
}
return;
}
V child = mViewRef.get();
if (child == null) {
return;
}
int top;
if (state == STATE_COLLAPSED) {
top = mMinOffset;
} else if (state == STATE_EXPANDED) {
top = mMaxOffset;
} else if (mHideable && state == STATE_HIDDEN) {
top = -child.getHeight();
} else {
throw new IllegalArgumentException("Illegal state argument: " + state);
}
setStateInternal(STATE_SETTLING);
if (mViewDragHelper.smoothSlideViewTo(child, child.getLeft(), top)) {
ViewCompat.postOnAnimation(child, new SettleRunnable(child, state));
}
}
/**
* Gets the current state of the bottom sheet.
*
* @return One of {@link #STATE_EXPANDED}, {@link #STATE_COLLAPSED}, {@link #STATE_DRAGGING},
* and {@link #STATE_SETTLING}.
*/
@State
public final int getState() {
return mState;
}
private void setStateInternal(@State int state) {
if (mState == state) {
return;
}
mState = state;
View bottomSheet = mViewRef.get();
if (bottomSheet != null && mCallback != null) {
mCallback.onStateChanged(bottomSheet, state);
}
}
private void reset() {
mActivePointerId = ViewDragHelper.INVALID_POINTER;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
private boolean shouldHide(View child, float yvel) {
if (child.getTop() > mMinOffset) {
// It should not hide, but collapse.
return false;
}
final float newTop = child.getTop() + yvel * HIDE_FRICTION;
return Math.abs(newTop - mMinOffset) / (float) mPeekHeight > HIDE_THRESHOLD;
}
private View findScrollingChild(View view) {
if (view instanceof NestedScrollingChild) {
return view;
}
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
for (int i = 0, count = group.getChildCount(); i < count; i++) {
View scrollingChild = findScrollingChild(group.getChildAt(i));
if (scrollingChild != null) {
return scrollingChild;
}
}
}
return null;
}
private float getYVelocity() {
mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
return mVelocityTracker.getYVelocity(mActivePointerId);
}
private final ViewDragHelper.Callback mDragCallback = new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(@NonNull View child, int pointerId) {
if (mState == STATE_DRAGGING) {
return false;
}
if (mTouchingScrollingChild) {
return false;
}
if (mState == STATE_EXPANDED && mActivePointerId == pointerId) {
View scroll = mNestedScrollingChildRef.get();
if (scroll != null && scroll.canScrollVertically(-1)) {
// Let the content scroll up
return false;
}
}
return mViewRef != null && mViewRef.get() == child;
}
@Override
public void onViewPositionChanged(@NonNull View changedView, int left, int top, int dx, int dy) {
dispatchOnSlide(top);
}
@Override
public void onViewDragStateChanged(int state) {
if (state == ViewDragHelper.STATE_DRAGGING) {
setStateInternal(STATE_DRAGGING);
}
}
@Override
public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) {
int top;
@State int targetState;
if (yvel > 0) { // Moving up
top = mMaxOffset;
targetState = STATE_EXPANDED;
} else if (mHideable && shouldHide(releasedChild, yvel)) {
top = -mViewRef.get().getHeight();
targetState = STATE_HIDDEN;
} else if (yvel == 0.f) {
int currentTop = releasedChild.getTop();
targetState = STATE_EXPANDED;
if (Math.abs(currentTop - mMinOffset) > Math.abs(currentTop - mMaxOffset)) {
top = mMaxOffset;
} else {
top = mMinOffset;
targetState = STATE_COLLAPSED;
}
} else {
top = mMinOffset;
targetState = STATE_COLLAPSED;
}
if (mViewDragHelper.settleCapturedViewAt(releasedChild.getLeft(), top)) {
setStateInternal(STATE_SETTLING);
ViewCompat.postOnAnimation(releasedChild,
new SettleRunnable(releasedChild, targetState));
} else {
setStateInternal(targetState);
}
}
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
return constrain(top, mHideable ? -child.getHeight() : mMinOffset, mMaxOffset);
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
return child.getLeft();
}
@Override
public int getViewVerticalDragRange(@NonNull View child) {
if (mHideable) {
return child.getHeight();
} else {
return mMaxOffset - mMinOffset;
}
}
};
private void dispatchOnSlide(int top) {
View bottomSheet = mViewRef.get();
if (bottomSheet != null && mCallback != null) {
if (top < mMinOffset) {
mCallback.onSlide(bottomSheet, (float) (top - mMinOffset) / mPeekHeight);
} else {
mCallback.onSlide(bottomSheet,
(float) (top - mMinOffset) / ((mMaxOffset - mMinOffset)));
}
}
}
private class SettleRunnable implements Runnable {
private final View mView;
@State
private final int mTargetState;
SettleRunnable(View view, @State int targetState) {
mView = view;
mTargetState = targetState;
}
@Override
public void run() {
if (mViewDragHelper != null && mViewDragHelper.continueSettling(true)) {
ViewCompat.postOnAnimation(mView, this);
} else {
setStateInternal(mTargetState);
}
}
}
protected static class SavedState extends AbsSavedState {
@State
final int state;
public SavedState(Parcel source, ClassLoader loader) {
super(source, loader);
state = source.readInt();
}
public SavedState(Parcelable superState, @State int state) {
super(superState);
this.state = state;
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(state);
}
public static final Creator<SavedState> CREATOR =
new ClassLoaderCreator<SavedState>() {
@Override
public SavedState createFromParcel(@NonNull Parcel in, ClassLoader loader) {
return new SavedState(in, loader);
}
@Override
public SavedState createFromParcel(@NonNull Parcel in) {
return new SavedState(in, null);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
/**
* A utility function to get the {@link TopSheetBehavior} associated with the {@code view}.
*
* @param view The {@link View} with {@link TopSheetBehavior}.
* @return The {@link TopSheetBehavior} associated with the {@code view}.
*/
@NonNull
@SuppressWarnings("unchecked")
public static <V extends View> TopSheetBehavior<V> from(@NonNull V view) {
ViewGroup.LayoutParams params = view.getLayoutParams();
if (!(params instanceof CoordinatorLayout.LayoutParams)) {
throw new IllegalArgumentException("The view is not a child of CoordinatorLayout");
}
CoordinatorLayout.Behavior<?> behavior =
((CoordinatorLayout.LayoutParams) params).getBehavior();
if (!(behavior instanceof TopSheetBehavior)) {
throw new IllegalArgumentException("The view is not associated with TopSheetBehavior");
}
return (TopSheetBehavior<V>) behavior;
}
static int constrain(int amount, int low, int high) {
return amount < low ? low : (Math.min(amount, high));
}
}