/
BottomSheetBehavior.java
2158 lines (1929 loc) · 75.1 KB
/
BottomSheetBehavior.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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.bottomsheet;
import com.google.android.material.R;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import androidx.annotation.FloatRange;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.RestrictTo;
import androidx.annotation.StringRes;
import androidx.annotation.VisibleForTesting;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout.LayoutParams;
import androidx.core.graphics.Insets;
import androidx.core.math.MathUtils;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat;
import androidx.core.view.accessibility.AccessibilityViewCommand;
import androidx.customview.view.AbsSavedState;
import androidx.customview.widget.ViewDragHelper;
import com.google.android.material.internal.ViewUtils;
import com.google.android.material.internal.ViewUtils.RelativePadding;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.ShapeAppearanceModel;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* An interaction behavior plugin for a child view of {@link CoordinatorLayout} to make it work as a
* bottom sheet.
*
* <p>To send useful accessibility events, set a title on bottom sheets that are windows or are
* window-like. For BottomSheetDialog use {@link BottomSheetDialog#setTitle(int)}, and for
* BottomSheetDialogFragment use {@link ViewCompat#setAccessibilityPaneTitle(View, CharSequence)}.
*/
public class BottomSheetBehavior<V extends View> extends CoordinatorLayout.Behavior<V> {
/** Callback for monitoring events about bottom sheets. */
public abstract static class BottomSheetCallback {
/**
* 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}, {@link
* #STATE_HIDDEN}, or {@link #STATE_HALF_EXPANDED}.
*/
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 [-1,1] range. Offset increases
* as this bottom sheet is moving upward. From 0 to 1 the sheet is between collapsed and
* expanded states and from -1 to 0 it is between hidden and collapsed states.
*/
public abstract void onSlide(@NonNull View bottomSheet, float slideOffset);
void onLayout(@NonNull View bottomSheet) {}
}
/** The bottom sheet is dragging. */
public static final int STATE_DRAGGING = 1;
/** The bottom sheet is settling. */
public static final int STATE_SETTLING = 2;
/** The bottom sheet is expanded. */
public static final int STATE_EXPANDED = 3;
/** The bottom sheet is collapsed. */
public static final int STATE_COLLAPSED = 4;
/** The bottom sheet is hidden. */
public static final int STATE_HIDDEN = 5;
/** The bottom sheet is half-expanded (used when fitToContents is false). */
public static final int STATE_HALF_EXPANDED = 6;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef({
STATE_EXPANDED,
STATE_COLLAPSED,
STATE_DRAGGING,
STATE_SETTLING,
STATE_HIDDEN,
STATE_HALF_EXPANDED
})
@Retention(RetentionPolicy.SOURCE)
public @interface State {}
/**
* Peek at the 16:9 ratio keyline of its parent.
*
* <p>This can be used as a parameter for {@link #setPeekHeight(int)}. {@link #getPeekHeight()}
* will return this when the value is set.
*/
public static final int PEEK_HEIGHT_AUTO = -1;
/** This flag will preserve the peekHeight int value on configuration change. */
public static final int SAVE_PEEK_HEIGHT = 0x1;
/** This flag will preserve the fitToContents boolean value on configuration change. */
public static final int SAVE_FIT_TO_CONTENTS = 1 << 1;
/** This flag will preserve the hideable boolean value on configuration change. */
public static final int SAVE_HIDEABLE = 1 << 2;
/** This flag will preserve the skipCollapsed boolean value on configuration change. */
public static final int SAVE_SKIP_COLLAPSED = 1 << 3;
/** This flag will preserve all aforementioned values on configuration change. */
public static final int SAVE_ALL = -1;
/**
* This flag will not preserve the aforementioned values set at runtime if the view is destroyed
* and recreated. The only value preserved will be the positional state, e.g. collapsed, hidden,
* expanded, etc. This is the default behavior.
*/
public static final int SAVE_NONE = 0;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
@IntDef(
flag = true,
value = {
SAVE_PEEK_HEIGHT,
SAVE_FIT_TO_CONTENTS,
SAVE_HIDEABLE,
SAVE_SKIP_COLLAPSED,
SAVE_ALL,
SAVE_NONE,
})
@Retention(RetentionPolicy.SOURCE)
public @interface SaveFlags {}
private static final String TAG = "BottomSheetBehavior";
@SaveFlags private int saveFlags = SAVE_NONE;
private static final int SIGNIFICANT_VEL_THRESHOLD = 500;
private static final float HIDE_THRESHOLD = 0.5f;
private static final float HIDE_FRICTION = 0.1f;
private static final int CORNER_ANIMATION_DURATION = 500;
private static final int NO_MAX_SIZE = -1;
private boolean fitToContents = true;
private boolean updateImportantForAccessibilityOnSiblings = false;
private float maximumVelocity;
/** Peek height set by the user. */
private int peekHeight;
/** Whether or not to use automatic peek height. */
private boolean peekHeightAuto;
/** Minimum peek height permitted. */
private int peekHeightMin;
/** Peek height gesture inset buffer to ensure enough swipeable space. */
private int peekHeightGestureInsetBuffer;
private MaterialShapeDrawable materialShapeDrawable;
@Nullable private ColorStateList backgroundTint;
private int maxWidth = NO_MAX_SIZE;
private int maxHeight = NO_MAX_SIZE;
private int gestureInsetBottom;
private boolean gestureInsetBottomIgnored;
private boolean paddingBottomSystemWindowInsets;
private boolean paddingLeftSystemWindowInsets;
private boolean paddingRightSystemWindowInsets;
private boolean paddingTopSystemWindowInsets;
private boolean marginLeftSystemWindowInsets;
private boolean marginRightSystemWindowInsets;
private boolean marginTopSystemWindowInsets;
private int insetBottom;
private int insetTop;
/** Default Shape Appearance to be used in bottomsheet */
private ShapeAppearanceModel shapeAppearanceModelDefault;
private boolean isShapeExpanded;
private SettleRunnable settleRunnable = null;
@Nullable private ValueAnimator interpolatorAnimator;
private static final int DEF_STYLE_RES = R.style.Widget_Design_BottomSheet_Modal;
int expandedOffset;
int fitToContentsOffset;
int halfExpandedOffset;
float halfExpandedRatio = 0.5f;
int collapsedOffset;
float elevation = -1;
boolean hideable;
private boolean skipCollapsed;
private boolean draggable = true;
@State int state = STATE_COLLAPSED;
@State int lastStableState = STATE_COLLAPSED;
@Nullable ViewDragHelper viewDragHelper;
private boolean ignoreEvents;
private int lastNestedScrollDy;
private boolean nestedScrolled;
private int childHeight;
int parentWidth;
int parentHeight;
@Nullable WeakReference<V> viewRef;
@Nullable WeakReference<View> nestedScrollingChildRef;
@NonNull private final ArrayList<BottomSheetCallback> callbacks = new ArrayList<>();
@Nullable private VelocityTracker velocityTracker;
int activePointerId;
private int initialY;
boolean touchingScrollingChild;
@Nullable private Map<View, Integer> importantForAccessibilityMap;
private int expandHalfwayActionId = View.NO_ID;
public BottomSheetBehavior() {}
public BottomSheetBehavior(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
peekHeightGestureInsetBuffer =
context.getResources().getDimensionPixelSize(R.dimen.mtrl_min_touch_target_size);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BottomSheetBehavior_Layout);
if (a.hasValue(R.styleable.BottomSheetBehavior_Layout_backgroundTint)) {
this.backgroundTint = MaterialResources.getColorStateList(
context, a, R.styleable.BottomSheetBehavior_Layout_backgroundTint);
}
if (a.hasValue(R.styleable.BottomSheetBehavior_Layout_shapeAppearance)) {
this.shapeAppearanceModelDefault =
ShapeAppearanceModel.builder(context, attrs, R.attr.bottomSheetStyle, DEF_STYLE_RES)
.build();
}
createMaterialShapeDrawableIfNeeded(context);
createShapeValueAnimator();
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
this.elevation = a.getDimension(R.styleable.BottomSheetBehavior_Layout_android_elevation, -1);
}
if (a.hasValue(R.styleable.BottomSheetBehavior_Layout_android_maxWidth)) {
setMaxWidth(
a.getDimensionPixelSize(
R.styleable.BottomSheetBehavior_Layout_android_maxWidth, NO_MAX_SIZE));
}
if (a.hasValue(R.styleable.BottomSheetBehavior_Layout_android_maxHeight)) {
setMaxHeight(
a.getDimensionPixelSize(
R.styleable.BottomSheetBehavior_Layout_android_maxHeight, NO_MAX_SIZE));
}
TypedValue value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight);
if (value != null && value.data == PEEK_HEIGHT_AUTO) {
setPeekHeight(value.data);
} else {
setPeekHeight(
a.getDimensionPixelSize(
R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight, PEEK_HEIGHT_AUTO));
}
setHideable(a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_hideable, false));
setGestureInsetBottomIgnored(
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_gestureInsetBottomIgnored, false));
setFitToContents(
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_fitToContents, true));
setSkipCollapsed(
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_skipCollapsed, false));
setDraggable(a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_draggable, true));
setSaveFlags(a.getInt(R.styleable.BottomSheetBehavior_Layout_behavior_saveFlags, SAVE_NONE));
setHalfExpandedRatio(
a.getFloat(R.styleable.BottomSheetBehavior_Layout_behavior_halfExpandedRatio, 0.5f));
value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_expandedOffset);
if (value != null && value.type == TypedValue.TYPE_FIRST_INT) {
setExpandedOffset(value.data);
} else {
setExpandedOffset(
a.getDimensionPixelOffset(
R.styleable.BottomSheetBehavior_Layout_behavior_expandedOffset, 0));
}
// Reading out if we are handling padding, so we can apply it to the content.
paddingBottomSystemWindowInsets =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_paddingBottomSystemWindowInsets, false);
paddingLeftSystemWindowInsets =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_paddingLeftSystemWindowInsets, false);
paddingRightSystemWindowInsets =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_paddingRightSystemWindowInsets, false);
// Setting this to false will prevent the bottomsheet from going below the status bar. Since
// this is a breaking change from the old behavior the default is true.
paddingTopSystemWindowInsets =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_paddingTopSystemWindowInsets, true);
marginLeftSystemWindowInsets =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_marginLeftSystemWindowInsets, false);
marginRightSystemWindowInsets =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_marginRightSystemWindowInsets, false);
marginTopSystemWindowInsets =
a.getBoolean(R.styleable.BottomSheetBehavior_Layout_marginTopSystemWindowInsets, false);
a.recycle();
ViewConfiguration configuration = ViewConfiguration.get(context);
maximumVelocity = configuration.getScaledMaximumFlingVelocity();
}
@NonNull
@Override
public Parcelable onSaveInstanceState(@NonNull CoordinatorLayout parent, @NonNull V child) {
return new SavedState(super.onSaveInstanceState(parent, child), this);
}
@Override
public void onRestoreInstanceState(
@NonNull CoordinatorLayout parent, @NonNull V child, @NonNull Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(parent, child, ss.getSuperState());
// Restore Optional State values designated by saveFlags
restoreOptionalState(ss);
// Intermediate states are restored as collapsed state
if (ss.state == STATE_DRAGGING || ss.state == STATE_SETTLING) {
this.state = STATE_COLLAPSED;
this.lastStableState = this.state;
} else {
this.state = ss.state;
this.lastStableState = this.state;
}
}
@Override
public void onAttachedToLayoutParams(@NonNull LayoutParams layoutParams) {
super.onAttachedToLayoutParams(layoutParams);
// These may already be null, but just be safe, explicitly assign them. This lets us know the
// first time we layout with this behavior by checking (viewRef == null).
viewRef = null;
viewDragHelper = null;
}
@Override
public void onDetachedFromLayoutParams() {
super.onDetachedFromLayoutParams();
// Release references so we don't run unnecessary codepaths while not attached to a view.
viewRef = null;
viewDragHelper = null;
}
@Override
public boolean onMeasureChild(
@NonNull CoordinatorLayout parent,
@NonNull V child,
int parentWidthMeasureSpec,
int widthUsed,
int parentHeightMeasureSpec,
int heightUsed) {
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidthMeasureSpec =
getChildMeasureSpec(
parentWidthMeasureSpec,
parent.getPaddingLeft()
+ parent.getPaddingRight()
+ lp.leftMargin
+ lp.rightMargin
+ widthUsed,
maxWidth,
lp.width);
int childHeightMeasureSpec =
getChildMeasureSpec(
parentHeightMeasureSpec,
parent.getPaddingTop()
+ parent.getPaddingBottom()
+ lp.topMargin
+ lp.bottomMargin
+ heightUsed,
maxHeight,
lp.height);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
return true; // Child was measured
}
private int getChildMeasureSpec(
int parentMeasureSpec, int padding, int maxSize, int childDimension) {
int result = ViewGroup.getChildMeasureSpec(parentMeasureSpec, padding, childDimension);
if (maxSize == NO_MAX_SIZE) {
return result;
} else {
int mode = MeasureSpec.getMode(result);
int size = MeasureSpec.getSize(result);
switch (mode) {
case MeasureSpec.EXACTLY:
return MeasureSpec.makeMeasureSpec(min(size, maxSize), MeasureSpec.EXACTLY);
case MeasureSpec.AT_MOST:
case MeasureSpec.UNSPECIFIED:
default:
return MeasureSpec.makeMeasureSpec(
size == 0 ? maxSize : min(size, maxSize), MeasureSpec.AT_MOST);
}
}
}
@Override
public boolean onLayoutChild(
@NonNull CoordinatorLayout parent, @NonNull final V child, int layoutDirection) {
if (ViewCompat.getFitsSystemWindows(parent) && !ViewCompat.getFitsSystemWindows(child)) {
child.setFitsSystemWindows(true);
}
if (viewRef == null) {
// First layout with this behavior.
peekHeightMin =
parent.getResources().getDimensionPixelSize(R.dimen.design_bottom_sheet_peek_height_min);
setWindowInsetsListener(child);
viewRef = new WeakReference<>(child);
// Only set MaterialShapeDrawable as background if shapeTheming is enabled, otherwise will
// default to android:background declared in styles or layout.
if (materialShapeDrawable != null) {
ViewCompat.setBackground(child, materialShapeDrawable);
// Use elevation attr if set on bottomsheet; otherwise, use elevation of child view.
materialShapeDrawable.setElevation(
elevation == -1 ? ViewCompat.getElevation(child) : elevation);
// Update the material shape based on initial state.
isShapeExpanded = state == STATE_EXPANDED;
materialShapeDrawable.setInterpolation(isShapeExpanded ? 0f : 1f);
} else if (backgroundTint != null) {
ViewCompat.setBackgroundTintList(child, backgroundTint);
}
updateAccessibilityActions();
if (ViewCompat.getImportantForAccessibility(child)
== ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
}
if (viewDragHelper == null) {
viewDragHelper = ViewDragHelper.create(parent, dragCallback);
}
int savedTop = child.getTop();
// First let the parent lay it out
parent.onLayoutChild(child, layoutDirection);
// Offset the bottom sheet
parentWidth = parent.getWidth();
parentHeight = parent.getHeight();
childHeight = child.getHeight();
if (parentHeight - childHeight < insetTop) {
if (paddingTopSystemWindowInsets) {
// If the bottomsheet would land in the middle of the status bar when fully expanded add
// extra space to make sure it goes all the way.
childHeight = parentHeight;
} else {
// If we don't want the bottomsheet to go under the status bar we cap its height
childHeight = parentHeight - insetTop;
}
}
fitToContentsOffset = max(0, parentHeight - childHeight);
calculateHalfExpandedOffset();
calculateCollapsedOffset();
if (state == STATE_EXPANDED) {
ViewCompat.offsetTopAndBottom(child, getExpandedOffset());
} else if (state == STATE_HALF_EXPANDED) {
ViewCompat.offsetTopAndBottom(child, halfExpandedOffset);
} else if (hideable && state == STATE_HIDDEN) {
ViewCompat.offsetTopAndBottom(child, parentHeight);
} else if (state == STATE_COLLAPSED) {
ViewCompat.offsetTopAndBottom(child, collapsedOffset);
} else if (state == STATE_DRAGGING || state == STATE_SETTLING) {
ViewCompat.offsetTopAndBottom(child, savedTop - child.getTop());
}
nestedScrollingChildRef = new WeakReference<>(findScrollingChild(child));
for (int i = 0; i < callbacks.size(); i++) {
callbacks.get(i).onLayout(child);
}
return true;
}
@Override
public boolean onInterceptTouchEvent(
@NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) {
if (!child.isShown() || !draggable) {
ignoreEvents = true;
return false;
}
int action = event.getActionMasked();
// Record the velocity
if (action == MotionEvent.ACTION_DOWN) {
reset();
}
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain();
}
velocityTracker.addMovement(event);
switch (action) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
touchingScrollingChild = false;
activePointerId = MotionEvent.INVALID_POINTER_ID;
// Reset the ignore flag
if (ignoreEvents) {
ignoreEvents = false;
return false;
}
break;
case MotionEvent.ACTION_DOWN:
int initialX = (int) event.getX();
initialY = (int) event.getY();
// Only intercept nested scrolling events here if the view not being moved by the
// ViewDragHelper.
if (state != STATE_SETTLING) {
View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null;
if (scroll != null && parent.isPointInChildBounds(scroll, initialX, initialY)) {
activePointerId = event.getPointerId(event.getActionIndex());
touchingScrollingChild = true;
}
}
ignoreEvents =
activePointerId == MotionEvent.INVALID_POINTER_ID
&& !parent.isPointInChildBounds(child, initialX, initialY);
break;
default: // fall out
}
if (!ignoreEvents
&& viewDragHelper != null
&& viewDragHelper.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 = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null;
return action == MotionEvent.ACTION_MOVE
&& scroll != null
&& !ignoreEvents
&& state != STATE_DRAGGING
&& !parent.isPointInChildBounds(scroll, (int) event.getX(), (int) event.getY())
&& viewDragHelper != null
&& Math.abs(initialY - event.getY()) > viewDragHelper.getTouchSlop();
}
@Override
public boolean onTouchEvent(
@NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) {
if (!child.isShown()) {
return false;
}
int action = event.getActionMasked();
if (state == STATE_DRAGGING && action == MotionEvent.ACTION_DOWN) {
return true;
}
if (shouldHandleDraggingWithHelper()) {
viewDragHelper.processTouchEvent(event);
}
// Record the velocity
if (action == MotionEvent.ACTION_DOWN) {
reset();
}
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain();
}
velocityTracker.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 (shouldHandleDraggingWithHelper() && action == MotionEvent.ACTION_MOVE && !ignoreEvents) {
if (Math.abs(initialY - event.getY()) > viewDragHelper.getTouchSlop()) {
viewDragHelper.captureChildView(child, event.getPointerId(event.getActionIndex()));
}
}
return !ignoreEvents;
}
@Override
public boolean onStartNestedScroll(
@NonNull CoordinatorLayout coordinatorLayout,
@NonNull V child,
@NonNull View directTargetChild,
@NonNull View target,
int axes,
int type) {
lastNestedScrollDy = 0;
nestedScrolled = false;
return (axes & 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,
int type) {
if (type == ViewCompat.TYPE_NON_TOUCH) {
// Ignore fling here. The ViewDragHelper handles it.
return;
}
View scrollingChild = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null;
if (isNestedScrollingCheckEnabled() && target != scrollingChild) {
return;
}
int currentTop = child.getTop();
int newTop = currentTop - dy;
if (dy > 0) { // Upward
if (newTop < getExpandedOffset()) {
consumed[1] = currentTop - getExpandedOffset();
ViewCompat.offsetTopAndBottom(child, -consumed[1]);
setStateInternal(STATE_EXPANDED);
} else {
if (!draggable) {
// Prevent dragging
return;
}
consumed[1] = dy;
ViewCompat.offsetTopAndBottom(child, -dy);
setStateInternal(STATE_DRAGGING);
}
} else if (dy < 0) { // Downward
if (!target.canScrollVertically(-1)) {
if (newTop <= collapsedOffset || hideable) {
if (!draggable) {
// Prevent dragging
return;
}
consumed[1] = dy;
ViewCompat.offsetTopAndBottom(child, -dy);
setStateInternal(STATE_DRAGGING);
} else {
consumed[1] = currentTop - collapsedOffset;
ViewCompat.offsetTopAndBottom(child, -consumed[1]);
setStateInternal(STATE_COLLAPSED);
}
}
}
dispatchOnSlide(child.getTop());
lastNestedScrollDy = dy;
nestedScrolled = true;
}
@Override
public void onStopNestedScroll(
@NonNull CoordinatorLayout coordinatorLayout,
@NonNull V child,
@NonNull View target,
int type) {
if (child.getTop() == getExpandedOffset()) {
setStateInternal(STATE_EXPANDED);
return;
}
if (isNestedScrollingCheckEnabled()
&& (nestedScrollingChildRef == null
|| target != nestedScrollingChildRef.get()
|| !nestedScrolled)) {
return;
}
int top;
int targetState;
if (lastNestedScrollDy > 0) {
if (fitToContents) {
top = fitToContentsOffset;
targetState = STATE_EXPANDED;
} else {
int currentTop = child.getTop();
if (currentTop > halfExpandedOffset) {
top = halfExpandedOffset;
targetState = STATE_HALF_EXPANDED;
} else {
top = getExpandedOffset();
targetState = STATE_EXPANDED;
}
}
} else if (hideable && shouldHide(child, getYVelocity())) {
top = parentHeight;
targetState = STATE_HIDDEN;
} else if (lastNestedScrollDy == 0) {
int currentTop = child.getTop();
if (fitToContents) {
if (Math.abs(currentTop - fitToContentsOffset) < Math.abs(currentTop - collapsedOffset)) {
top = fitToContentsOffset;
targetState = STATE_EXPANDED;
} else {
top = collapsedOffset;
targetState = STATE_COLLAPSED;
}
} else {
if (currentTop < halfExpandedOffset) {
if (currentTop < Math.abs(currentTop - collapsedOffset)) {
top = getExpandedOffset();
targetState = STATE_EXPANDED;
} else {
if (shouldSkipHalfExpandedStateWhenDragging()) {
top = collapsedOffset;
targetState = STATE_COLLAPSED;
} else {
top = halfExpandedOffset;
targetState = STATE_HALF_EXPANDED;
}
}
} else {
if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) {
top = halfExpandedOffset;
targetState = STATE_HALF_EXPANDED;
} else {
top = collapsedOffset;
targetState = STATE_COLLAPSED;
}
}
}
} else {
if (fitToContents) {
top = collapsedOffset;
targetState = STATE_COLLAPSED;
} else {
// Settle to nearest height.
int currentTop = child.getTop();
if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) {
top = halfExpandedOffset;
targetState = STATE_HALF_EXPANDED;
} else {
top = collapsedOffset;
targetState = STATE_COLLAPSED;
}
}
}
startSettlingAnimation(child, targetState, top, false);
nestedScrolled = false;
}
@Override
public void onNestedScroll(
@NonNull CoordinatorLayout coordinatorLayout,
@NonNull V child,
@NonNull View target,
int dxConsumed,
int dyConsumed,
int dxUnconsumed,
int dyUnconsumed,
int type,
@NonNull int[] consumed) {
// Overridden to prevent the default consumption of the entire scroll distance.
}
@Override
public boolean onNestedPreFling(
@NonNull CoordinatorLayout coordinatorLayout,
@NonNull V child,
@NonNull View target,
float velocityX,
float velocityY) {
if (isNestedScrollingCheckEnabled() && nestedScrollingChildRef != null) {
return target == nestedScrollingChildRef.get()
&& (state != STATE_EXPANDED
|| super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY));
} else {
return false;
}
}
/**
* @return whether the height of the expanded sheet is determined by the height of its contents,
* or if it is expanded in two stages (half the height of the parent container, full height of
* parent container).
*/
public boolean isFitToContents() {
return fitToContents;
}
/**
* Sets whether the height of the expanded sheet is determined by the height of its contents, or
* if it is expanded in two stages (half the height of the parent container, full height of parent
* container). Default value is true.
*
* @param fitToContents whether or not to fit the expanded sheet to its contents.
*/
public void setFitToContents(boolean fitToContents) {
if (this.fitToContents == fitToContents) {
return;
}
this.fitToContents = fitToContents;
// If sheet is already laid out, recalculate the collapsed offset based on new setting.
// Otherwise, let onLayoutChild handle this later.
if (viewRef != null) {
calculateCollapsedOffset();
}
// Fix incorrect expanded settings depending on whether or not we are fitting sheet to contents.
setStateInternal((this.fitToContents && state == STATE_HALF_EXPANDED) ? STATE_EXPANDED : state);
updateAccessibilityActions();
}
/**
* Sets the maximum width of the bottom sheet. The layout will be at most this dimension wide.
* This method should be called before {@link BottomSheetDialog#show()} in order for the width to
* be adjusted as expected.
*
* @param maxWidth The maximum width in pixels to be set
* @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_android_maxWidth
* @see #getMaxWidth()
*/
public void setMaxWidth(@Px int maxWidth) {
this.maxWidth = maxWidth;
}
/**
* Returns the bottom sheet's maximum width, or -1 if no maximum width is set.
*
* @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_android_maxWidth
* @see #setMaxWidth(int)
*/
@Px
public int getMaxWidth() {
return maxWidth;
}
/**
* Sets the maximum height of the bottom sheet. This method should be called before {@link
* BottomSheetDialog#show()} in order for the height to be adjusted as expected.
*
* @param maxHeight The maximum height in pixels to be set
* @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_android_maxHeight
* @see #getMaxHeight()
*/
public void setMaxHeight(@Px int maxHeight) {
this.maxHeight = maxHeight;
}
/**
* Returns the bottom sheet's maximum height, or -1 if no maximum height is set.
*
* @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_android_maxHeight
* @see #setMaxHeight(int)
*/
@Px
public int getMaxHeight() {
return maxHeight;
}
/**
* Sets the height of the bottom sheet when it is collapsed.
*
* @param peekHeight The height of the collapsed bottom sheet in pixels, or {@link
* #PEEK_HEIGHT_AUTO} to configure the sheet to peek automatically at 16:9 ratio keyline.
* @attr ref
* com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight
*/
public void setPeekHeight(int peekHeight) {
setPeekHeight(peekHeight, false);
}
/**
* Sets the height of the bottom sheet when it is collapsed while optionally animating between the
* old height and the new height.
*
* @param peekHeight The height of the collapsed bottom sheet in pixels, or {@link
* #PEEK_HEIGHT_AUTO} to configure the sheet to peek automatically at 16:9 ratio keyline.
* @param animate Whether to animate between the old height and the new height.
* @attr ref
* com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight
*/
public final void setPeekHeight(int peekHeight, boolean animate) {
boolean layout = false;
if (peekHeight == PEEK_HEIGHT_AUTO) {
if (!peekHeightAuto) {
peekHeightAuto = true;
layout = true;
}
} else if (peekHeightAuto || this.peekHeight != peekHeight) {
peekHeightAuto = false;
this.peekHeight = max(0, peekHeight);
layout = true;
}
// If sheet is already laid out, recalculate the collapsed offset based on new setting.
// Otherwise, let onLayoutChild handle this later.
if (layout) {
updatePeekHeight(animate);
}
}
private void updatePeekHeight(boolean animate) {
if (viewRef != null) {
calculateCollapsedOffset();
if (state == STATE_COLLAPSED) {
V view = viewRef.get();
if (view != null) {
if (animate) {
settleToStatePendingLayout(state);
} else {
view.requestLayout();
}
}
}
}
}
/**
* Gets the height of the bottom sheet when it is collapsed.
*
* @return The height of the collapsed bottom sheet in pixels, or {@link #PEEK_HEIGHT_AUTO} if the
* sheet is configured to peek automatically at 16:9 ratio keyline
* @attr ref
* com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight
*/
public int getPeekHeight() {
return peekHeightAuto ? PEEK_HEIGHT_AUTO : peekHeight;
}
/**
* Determines the height of the BottomSheet in the {@link #STATE_HALF_EXPANDED} state. The
* material guidelines recommended a value of 0.5, which results in the sheet filling half of the