react-native-sheet2 1.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +79 -0
  3. package/android/build.gradle +83 -0
  4. package/android/gradle.properties +6 -0
  5. package/android/src/main/AndroidManifest.xml +12 -0
  6. package/android/src/main/java/com/behavior/BottomSheetBehavior.java +2329 -0
  7. package/android/src/main/java/com/behavior/InsetsAnimationCallback.java +83 -0
  8. package/android/src/main/java/com/modal/FullScreenDialog.kt +100 -0
  9. package/android/src/main/java/com/modal/TopModalView.kt +77 -0
  10. package/android/src/main/java/com/modal/TopModalViewManager.kt +83 -0
  11. package/android/src/main/java/com/modal/TopModalViewModule.kt +36 -0
  12. package/android/src/main/java/com/sheet/AppFittedSheet.kt +149 -0
  13. package/android/src/main/java/com/sheet/BaseRNView.kt +73 -0
  14. package/android/src/main/java/com/sheet/CustomBottomSheetDialog.java +238 -0
  15. package/android/src/main/java/com/sheet/DialogRootViewGroup.kt +159 -0
  16. package/android/src/main/java/com/sheet/FragmentModalBottomSheet.kt +54 -0
  17. package/android/src/main/java/com/sheet/ReactNativeReflection.java +24 -0
  18. package/android/src/main/java/com/sheet/SheetPackage.kt +20 -0
  19. package/android/src/main/java/com/sheet/SheetViewManager.kt +144 -0
  20. package/android/src/main/java/com/sheet/SheetViewModule.kt +43 -0
  21. package/android/src/main/java/com/sheet/utils.kt +71 -0
  22. package/android/src/main/java/com/transparent/activity/ActivityModalView.kt +71 -0
  23. package/android/src/main/java/com/transparent/activity/TransparentActivity.kt +48 -0
  24. package/android/src/main/java/com/transparent/activity/TransparentActivityManager.kt +63 -0
  25. package/android/src/main/java/com/transparent/activity/TransparentActivityModule.kt +28 -0
  26. package/android/src/main/res/anim/fade_in.xml +8 -0
  27. package/android/src/main/res/anim/fade_out.xml +11 -0
  28. package/android/src/main/res/anim/slide_down.xml +8 -0
  29. package/android/src/main/res/anim/slide_up.xml +8 -0
  30. package/android/src/main/res/layout/dialog_bottom_sheet.xml +64 -0
  31. package/android/src/main/res/layout/item_full.xml +14 -0
  32. package/android/src/main/res/values/colors.xml +15 -0
  33. package/android/src/main/res/values/styles.xml +75 -0
  34. package/ios/FittedSheets/Compatible.swift +55 -0
  35. package/ios/FittedSheets/InitialTouchPanGestureRecognizer.swift +19 -0
  36. package/ios/FittedSheets/SheetContentViewController.swift +326 -0
  37. package/ios/FittedSheets/SheetContentViewDelegate.swift +17 -0
  38. package/ios/FittedSheets/SheetOptions.swift +100 -0
  39. package/ios/FittedSheets/SheetSize.swift +20 -0
  40. package/ios/FittedSheets/SheetTransition.swift +153 -0
  41. package/ios/FittedSheets/SheetView.swift +21 -0
  42. package/ios/FittedSheets/SheetViewController.swift +761 -0
  43. package/ios/FittedSheets/SheetViewDelegate.swift +16 -0
  44. package/ios/FittedSheets/UIColorExtension.swift +59 -0
  45. package/ios/FittedSheets/UIViewControllerExtension.swift +27 -0
  46. package/ios/FittedSheets/Yalta.swift +420 -0
  47. package/ios/LBBottomSheet/BottomSheetConstant.swift +48 -0
  48. package/ios/LBBottomSheet/Model/BottomSheetController+Behavior.swift +262 -0
  49. package/ios/LBBottomSheet/Model/BottomSheetController+Theme.swift +156 -0
  50. package/ios/LBBottomSheet/Protocols/BottomSheetInteractionDelegate.swift +29 -0
  51. package/ios/LBBottomSheet/Protocols/BottomSheetPositionDelegate.swift +31 -0
  52. package/ios/LBBottomSheet/UI/BottomSheet.storyboard +105 -0
  53. package/ios/LBBottomSheet/UI/BottomSheetController.swift +601 -0
  54. package/ios/LBBottomSheet/Utils/Components/ForwardingEventsView.swift +60 -0
  55. package/ios/LBBottomSheet/Utils/Extensions/CACornerMask+Extension.swift +33 -0
  56. package/ios/LBBottomSheet/Utils/Extensions/Mirror+Extension.swift +47 -0
  57. package/ios/LBBottomSheet/Utils/Extensions/UIApplication+Extension.swift +35 -0
  58. package/ios/LBBottomSheet/Utils/Extensions/UIColor+Extension.swift +61 -0
  59. package/ios/LBBottomSheet/Utils/Extensions/UIGestureRecognizer+Extensions.swift +28 -0
  60. package/ios/LBBottomSheet/Utils/Extensions/UIScreen+Extension.swift +28 -0
  61. package/ios/LBBottomSheet/Utils/Extensions/UIScrollView+Extension.swift +25 -0
  62. package/ios/LBBottomSheet/Utils/Extensions/UIView+Extension.swift +52 -0
  63. package/ios/LBBottomSheet/Utils/Extensions/UIViewController+Extension.swift +104 -0
  64. package/ios/Sheet-Bridging-Header.h +1 -0
  65. package/ios/Sheet.xcodeproj/project.pbxproj +377 -0
  66. package/ios/SheetViewManager.m +27 -0
  67. package/ios/SheetViewManager.swift +351 -0
  68. package/ios/TopModalViewManager.swift +196 -0
  69. package/package.json +103 -0
  70. package/react-native-sheet.podspec +21 -0
  71. package/src/FittedSheet.tsx +177 -0
  72. package/src/TopModal.tsx +94 -0
  73. package/src/TransparentActivity.tsx +98 -0
  74. package/src/index.tsx +16 -0
@@ -0,0 +1,2329 @@
1
+ /*
2
+ * Copyright (C) 2015 The Android Open Source Project
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ package com.behavior;
18
+
19
+ import com.google.android.material.R;
20
+
21
+ import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
22
+ import static java.lang.Math.max;
23
+ import static java.lang.Math.min;
24
+
25
+ import android.animation.ValueAnimator;
26
+ import android.animation.ValueAnimator.AnimatorUpdateListener;
27
+ import android.content.Context;
28
+ import android.content.res.ColorStateList;
29
+ import android.content.res.TypedArray;
30
+ import android.os.Build;
31
+ import android.os.Build.VERSION;
32
+ import android.os.Build.VERSION_CODES;
33
+ import android.os.Parcel;
34
+ import android.os.Parcelable;
35
+ import android.util.AttributeSet;
36
+ import android.util.Log;
37
+ import android.util.SparseIntArray;
38
+ import android.util.TypedValue;
39
+ import android.view.MotionEvent;
40
+ import android.view.VelocityTracker;
41
+ import android.view.View;
42
+ import android.view.View.MeasureSpec;
43
+ import android.view.ViewConfiguration;
44
+ import android.view.ViewGroup;
45
+ import android.view.ViewGroup.MarginLayoutParams;
46
+ import android.view.ViewParent;
47
+ import android.view.accessibility.AccessibilityEvent;
48
+
49
+ import androidx.annotation.FloatRange;
50
+ import androidx.annotation.IntDef;
51
+ import androidx.annotation.NonNull;
52
+ import androidx.annotation.Nullable;
53
+ import androidx.annotation.Px;
54
+ import androidx.annotation.RestrictTo;
55
+ import androidx.annotation.StringRes;
56
+ import androidx.annotation.VisibleForTesting;
57
+ import androidx.coordinatorlayout.widget.CoordinatorLayout;
58
+ import androidx.coordinatorlayout.widget.CoordinatorLayout.LayoutParams;
59
+ import androidx.core.graphics.Insets;
60
+ import androidx.core.math.MathUtils;
61
+ import androidx.core.view.ViewCompat;
62
+ import androidx.core.view.WindowInsetsCompat;
63
+ import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
64
+ import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat;
65
+ import androidx.core.view.accessibility.AccessibilityViewCommand;
66
+ import androidx.customview.view.AbsSavedState;
67
+ import androidx.customview.widget.ViewDragHelper;
68
+ import com.google.android.material.internal.ViewUtils;
69
+ import com.google.android.material.internal.ViewUtils.RelativePadding;
70
+ import com.google.android.material.resources.MaterialResources;
71
+ import com.google.android.material.shape.MaterialShapeDrawable;
72
+ import com.google.android.material.shape.ShapeAppearanceModel;
73
+ import java.lang.annotation.Retention;
74
+ import java.lang.annotation.RetentionPolicy;
75
+ import java.lang.ref.WeakReference;
76
+ import java.util.ArrayList;
77
+ import java.util.HashMap;
78
+ import java.util.Map;
79
+
80
+ /**
81
+ * An interaction behavior plugin for a child view of {@link CoordinatorLayout} to make it work as a
82
+ * bottom sheet.
83
+ *
84
+ * <p>To send useful accessibility events, set a title on bottom sheets that are windows or are
85
+ * window-like. For BottomSheetDialog use {@link BottomSheetDialog#setTitle(int)}, and for
86
+ * BottomSheetDialogFragment use {@link ViewCompat#setAccessibilityPaneTitle(View, CharSequence)}.
87
+ */
88
+ public class BottomSheetBehavior<V extends View> extends CoordinatorLayout.Behavior<V> {
89
+
90
+ /** Callback for monitoring events about bottom sheets. */
91
+ public abstract static class BottomSheetCallback {
92
+
93
+ /**
94
+ * Called when the bottom sheet changes its state.
95
+ *
96
+ * @param bottomSheet The bottom sheet view.
97
+ * @param newState The new state. This will be one of {@link #STATE_DRAGGING}, {@link
98
+ * #STATE_SETTLING}, {@link #STATE_EXPANDED}, {@link #STATE_COLLAPSED}, {@link
99
+ * #STATE_HIDDEN}, or {@link #STATE_HALF_EXPANDED}.
100
+ */
101
+ public abstract void onStateChanged(@NonNull View bottomSheet, @State int newState);
102
+
103
+ /**
104
+ * Called when the bottom sheet is being dragged.
105
+ *
106
+ * @param bottomSheet The bottom sheet view.
107
+ * @param slideOffset The new offset of this bottom sheet within [-1,1] range. Offset increases
108
+ * as this bottom sheet is moving upward. From 0 to 1 the sheet is between collapsed and
109
+ * expanded states and from -1 to 0 it is between hidden and collapsed states.
110
+ */
111
+ public abstract void onSlide(@NonNull View bottomSheet, float slideOffset);
112
+
113
+ void onLayout(@NonNull View bottomSheet) {}
114
+ }
115
+
116
+ /** The bottom sheet is dragging. */
117
+ public static final int STATE_DRAGGING = 1;
118
+
119
+ /** The bottom sheet is settling. */
120
+ public static final int STATE_SETTLING = 2;
121
+
122
+ /** The bottom sheet is expanded. */
123
+ public static final int STATE_EXPANDED = 3;
124
+
125
+ /** The bottom sheet is collapsed. */
126
+ public static final int STATE_COLLAPSED = 4;
127
+
128
+ /** The bottom sheet is hidden. */
129
+ public static final int STATE_HIDDEN = 5;
130
+
131
+ /** The bottom sheet is half-expanded (used when fitToContents is false). */
132
+ public static final int STATE_HALF_EXPANDED = 6;
133
+
134
+ /** @hide */
135
+ @RestrictTo(LIBRARY_GROUP)
136
+ @IntDef({
137
+ STATE_EXPANDED,
138
+ STATE_COLLAPSED,
139
+ STATE_DRAGGING,
140
+ STATE_SETTLING,
141
+ STATE_HIDDEN,
142
+ STATE_HALF_EXPANDED
143
+ })
144
+ @Retention(RetentionPolicy.SOURCE)
145
+ public @interface State {}
146
+
147
+ /**
148
+ * Stable states that can be set by the {@link #setState(int)} method. These includes all the
149
+ * possible states a bottom sheet can be in when it's settled.
150
+ *
151
+ * @hide
152
+ */
153
+ @RestrictTo(LIBRARY_GROUP)
154
+ @IntDef({STATE_EXPANDED, STATE_COLLAPSED, STATE_HIDDEN, STATE_HALF_EXPANDED})
155
+ @Retention(RetentionPolicy.SOURCE)
156
+ public @interface StableState {}
157
+
158
+ /**
159
+ * Peek at the 16:9 ratio keyline of its parent.
160
+ *
161
+ * <p>This can be used as a parameter for {@link #setPeekHeight(int)}. {@link #getPeekHeight()}
162
+ * will return this when the value is set.
163
+ */
164
+ public static final int PEEK_HEIGHT_AUTO = -1;
165
+
166
+ /** This flag will preserve the peekHeight int value on configuration change. */
167
+ public static final int SAVE_PEEK_HEIGHT = 0x1;
168
+
169
+ /** This flag will preserve the fitToContents boolean value on configuration change. */
170
+ public static final int SAVE_FIT_TO_CONTENTS = 1 << 1;
171
+
172
+ /** This flag will preserve the hideable boolean value on configuration change. */
173
+ public static final int SAVE_HIDEABLE = 1 << 2;
174
+
175
+ /** This flag will preserve the skipCollapsed boolean value on configuration change. */
176
+ public static final int SAVE_SKIP_COLLAPSED = 1 << 3;
177
+
178
+ /** This flag will preserve all aforementioned values on configuration change. */
179
+ public static final int SAVE_ALL = -1;
180
+
181
+ /**
182
+ * This flag will not preserve the aforementioned values set at runtime if the view is destroyed
183
+ * and recreated. The only value preserved will be the positional state, e.g. collapsed, hidden,
184
+ * expanded, etc. This is the default behavior.
185
+ */
186
+ public static final int SAVE_NONE = 0;
187
+
188
+ /** @hide */
189
+ @RestrictTo(LIBRARY_GROUP)
190
+ @IntDef(
191
+ flag = true,
192
+ value = {
193
+ SAVE_PEEK_HEIGHT,
194
+ SAVE_FIT_TO_CONTENTS,
195
+ SAVE_HIDEABLE,
196
+ SAVE_SKIP_COLLAPSED,
197
+ SAVE_ALL,
198
+ SAVE_NONE,
199
+ })
200
+ @Retention(RetentionPolicy.SOURCE)
201
+ public @interface SaveFlags {}
202
+
203
+ private static final String TAG = "BottomSheetBehavior";
204
+
205
+ @SaveFlags private int saveFlags = SAVE_NONE;
206
+
207
+ @VisibleForTesting static final int DEFAULT_SIGNIFICANT_VEL_THRESHOLD = 500;
208
+
209
+ private static final float HIDE_THRESHOLD = 0.5f;
210
+
211
+ private static final float HIDE_FRICTION = 0.1f;
212
+
213
+ private static final int CORNER_ANIMATION_DURATION = 500;
214
+
215
+ private static final int NO_MAX_SIZE = -1;
216
+
217
+ private static final int VIEW_INDEX_BOTTOM_SHEET = 0;
218
+
219
+ @VisibleForTesting
220
+ static final int VIEW_INDEX_ACCESSIBILITY_DELEGATE_VIEW = 1;
221
+
222
+ private boolean fitToContents = true;
223
+
224
+ private boolean updateImportantForAccessibilityOnSiblings = false;
225
+
226
+ private float maximumVelocity;
227
+
228
+ private int significantVelocityThreshold;
229
+
230
+ /** Peek height set by the user. */
231
+ private int peekHeight;
232
+
233
+ /** Whether or not to use automatic peek height. */
234
+ private boolean peekHeightAuto;
235
+
236
+ /** Minimum peek height permitted. */
237
+ private int peekHeightMin;
238
+
239
+ /** Peek height gesture inset buffer to ensure enough swipeable space. */
240
+ private int peekHeightGestureInsetBuffer;
241
+
242
+ private MaterialShapeDrawable materialShapeDrawable;
243
+
244
+ @Nullable private ColorStateList backgroundTint;
245
+
246
+ private int maxWidth = NO_MAX_SIZE;
247
+
248
+ private int maxHeight = NO_MAX_SIZE;
249
+
250
+ private int gestureInsetBottom;
251
+ private boolean gestureInsetBottomIgnored;
252
+ private boolean paddingBottomSystemWindowInsets;
253
+ private boolean paddingLeftSystemWindowInsets;
254
+ private boolean paddingRightSystemWindowInsets;
255
+ private boolean paddingTopSystemWindowInsets;
256
+ private boolean marginLeftSystemWindowInsets;
257
+ private boolean marginRightSystemWindowInsets;
258
+ private boolean marginTopSystemWindowInsets;
259
+
260
+ private int insetBottom;
261
+ private int insetTop;
262
+
263
+ private boolean shouldRemoveExpandedCorners;
264
+
265
+ /** Default Shape Appearance to be used in bottomsheet */
266
+ private ShapeAppearanceModel shapeAppearanceModelDefault;
267
+
268
+ private boolean expandedCornersRemoved;
269
+
270
+ private final StateSettlingTracker stateSettlingTracker = new StateSettlingTracker();
271
+
272
+ @Nullable private ValueAnimator interpolatorAnimator;
273
+
274
+ private static final int DEF_STYLE_RES = R.style.Widget_Design_BottomSheet_Modal;
275
+
276
+ int expandedOffset;
277
+
278
+ int fitToContentsOffset;
279
+
280
+ int halfExpandedOffset;
281
+
282
+ float halfExpandedRatio = 0.5f;
283
+
284
+ int collapsedOffset;
285
+
286
+ float elevation = -1;
287
+
288
+ boolean hideable;
289
+
290
+ private boolean skipCollapsed;
291
+
292
+ private boolean draggable = true;
293
+
294
+ @State int state = STATE_COLLAPSED;
295
+
296
+ @State int lastStableState = STATE_COLLAPSED;
297
+
298
+ @Nullable ViewDragHelper viewDragHelper;
299
+
300
+ private boolean ignoreEvents;
301
+ private boolean isHorizontalPanning = false;
302
+
303
+ private int lastNestedScrollDy;
304
+
305
+ private boolean nestedScrolled;
306
+
307
+ private float hideFriction = HIDE_FRICTION;
308
+
309
+ private int childHeight;
310
+ int parentWidth;
311
+ int parentHeight;
312
+
313
+ @Nullable WeakReference<V> viewRef;
314
+ @Nullable WeakReference<View> accessibilityDelegateViewRef;
315
+
316
+ @Nullable WeakReference<View> nestedScrollingChildRef;
317
+
318
+ public void setNewNestedScrollView(View view) {
319
+ view.setNestedScrollingEnabled(true);
320
+ nestedScrollingChildRef = new WeakReference<>(view);
321
+ }
322
+
323
+ @NonNull private final ArrayList<BottomSheetCallback> callbacks = new ArrayList<>();
324
+
325
+ @Nullable private VelocityTracker velocityTracker;
326
+
327
+ int activePointerId;
328
+
329
+ private int initialY;
330
+ private int initialX;
331
+
332
+ boolean touchingScrollingChild;
333
+
334
+ @Nullable private Map<View, Integer> importantForAccessibilityMap;
335
+
336
+ @VisibleForTesting
337
+ final SparseIntArray expandHalfwayActionIds = new SparseIntArray();
338
+
339
+ public BottomSheetBehavior() {}
340
+
341
+ public BottomSheetBehavior(@NonNull Context context, @Nullable AttributeSet attrs) {
342
+ super(context, attrs);
343
+
344
+ peekHeightGestureInsetBuffer =
345
+ context.getResources().getDimensionPixelSize(R.dimen.mtrl_min_touch_target_size);
346
+
347
+ TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BottomSheetBehavior_Layout);
348
+ if (a.hasValue(R.styleable.BottomSheetBehavior_Layout_backgroundTint)) {
349
+ this.backgroundTint = MaterialResources.getColorStateList(
350
+ context, a, R.styleable.BottomSheetBehavior_Layout_backgroundTint);
351
+ }
352
+ if (a.hasValue(R.styleable.BottomSheetBehavior_Layout_shapeAppearance)) {
353
+ this.shapeAppearanceModelDefault =
354
+ ShapeAppearanceModel.builder(context, attrs, R.attr.bottomSheetStyle, DEF_STYLE_RES)
355
+ .build();
356
+ }
357
+ createMaterialShapeDrawableIfNeeded(context);
358
+ createShapeValueAnimator();
359
+
360
+ if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
361
+ this.elevation = a.getDimension(R.styleable.BottomSheetBehavior_Layout_android_elevation, -1);
362
+ }
363
+
364
+ if (a.hasValue(R.styleable.BottomSheetBehavior_Layout_android_maxWidth)) {
365
+ setMaxWidth(
366
+ a.getDimensionPixelSize(
367
+ R.styleable.BottomSheetBehavior_Layout_android_maxWidth, NO_MAX_SIZE));
368
+ }
369
+
370
+ if (a.hasValue(R.styleable.BottomSheetBehavior_Layout_android_maxHeight)) {
371
+ setMaxHeight(
372
+ a.getDimensionPixelSize(
373
+ R.styleable.BottomSheetBehavior_Layout_android_maxHeight, NO_MAX_SIZE));
374
+ }
375
+
376
+ TypedValue value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight);
377
+ if (value != null && value.data == PEEK_HEIGHT_AUTO) {
378
+ setPeekHeight(value.data);
379
+ } else {
380
+ setPeekHeight(
381
+ a.getDimensionPixelSize(
382
+ R.styleable.BottomSheetBehavior_Layout_behavior_peekHeight, PEEK_HEIGHT_AUTO));
383
+ }
384
+ setHideable(a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_hideable, false));
385
+ setGestureInsetBottomIgnored(
386
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_gestureInsetBottomIgnored, false));
387
+ setFitToContents(
388
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_fitToContents, true));
389
+ setSkipCollapsed(
390
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_skipCollapsed, false));
391
+ setDraggable(a.getBoolean(R.styleable.BottomSheetBehavior_Layout_behavior_draggable, true));
392
+ setSaveFlags(a.getInt(R.styleable.BottomSheetBehavior_Layout_behavior_saveFlags, SAVE_NONE));
393
+ setHalfExpandedRatio(
394
+ a.getFloat(R.styleable.BottomSheetBehavior_Layout_behavior_halfExpandedRatio, 0.5f));
395
+
396
+ value = a.peekValue(R.styleable.BottomSheetBehavior_Layout_behavior_expandedOffset);
397
+ if (value != null && value.type == TypedValue.TYPE_FIRST_INT) {
398
+ setExpandedOffset(value.data);
399
+ } else {
400
+ setExpandedOffset(
401
+ a.getDimensionPixelOffset(
402
+ R.styleable.BottomSheetBehavior_Layout_behavior_expandedOffset, 0));
403
+ }
404
+
405
+ setSignificantVelocityThreshold(
406
+ a.getInt(
407
+ R.styleable.BottomSheetBehavior_Layout_behavior_significantVelocityThreshold,
408
+ DEFAULT_SIGNIFICANT_VEL_THRESHOLD));
409
+
410
+ // Reading out if we are handling padding, so we can apply it to the content.
411
+ paddingBottomSystemWindowInsets =
412
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_paddingBottomSystemWindowInsets, false);
413
+ paddingLeftSystemWindowInsets =
414
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_paddingLeftSystemWindowInsets, false);
415
+ paddingRightSystemWindowInsets =
416
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_paddingRightSystemWindowInsets, false);
417
+ // Setting this to false will prevent the bottomsheet from going below the status bar. Since
418
+ // this is a breaking change from the old behavior the default is true.
419
+ paddingTopSystemWindowInsets =
420
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_paddingTopSystemWindowInsets, true);
421
+ marginLeftSystemWindowInsets =
422
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_marginLeftSystemWindowInsets, false);
423
+ marginRightSystemWindowInsets =
424
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_marginRightSystemWindowInsets, false);
425
+ marginTopSystemWindowInsets =
426
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_marginTopSystemWindowInsets, false);
427
+ shouldRemoveExpandedCorners =
428
+ a.getBoolean(R.styleable.BottomSheetBehavior_Layout_shouldRemoveExpandedCorners, true);
429
+
430
+ a.recycle();
431
+ ViewConfiguration configuration = ViewConfiguration.get(context);
432
+ maximumVelocity = configuration.getScaledMaximumFlingVelocity();
433
+ }
434
+
435
+ @NonNull
436
+ @Override
437
+ public Parcelable onSaveInstanceState(@NonNull CoordinatorLayout parent, @NonNull V child) {
438
+ return new SavedState(super.onSaveInstanceState(parent, child), this);
439
+ }
440
+
441
+ @Override
442
+ public void onRestoreInstanceState(
443
+ @NonNull CoordinatorLayout parent, @NonNull V child, @NonNull Parcelable state) {
444
+ SavedState ss = (SavedState) state;
445
+ super.onRestoreInstanceState(parent, child, ss.getSuperState());
446
+ // Restore Optional State values designated by saveFlags
447
+ restoreOptionalState(ss);
448
+ // Intermediate states are restored as collapsed state
449
+ if (ss.state == STATE_DRAGGING || ss.state == STATE_SETTLING) {
450
+ this.state = STATE_COLLAPSED;
451
+ this.lastStableState = this.state;
452
+ } else {
453
+ this.state = ss.state;
454
+ this.lastStableState = this.state;
455
+ }
456
+ }
457
+
458
+ @Override
459
+ public void onAttachedToLayoutParams(@NonNull LayoutParams layoutParams) {
460
+ super.onAttachedToLayoutParams(layoutParams);
461
+ // These may already be null, but just be safe, explicitly assign them. This lets us know the
462
+ // first time we layout with this behavior by checking (viewRef == null).
463
+ viewRef = null;
464
+ viewDragHelper = null;
465
+ }
466
+
467
+ @Override
468
+ public void onDetachedFromLayoutParams() {
469
+ super.onDetachedFromLayoutParams();
470
+ // Release references so we don't run unnecessary codepaths while not attached to a view.
471
+ viewRef = null;
472
+ viewDragHelper = null;
473
+ }
474
+
475
+ @Override
476
+ public boolean onMeasureChild(
477
+ @NonNull CoordinatorLayout parent,
478
+ @NonNull V child,
479
+ int parentWidthMeasureSpec,
480
+ int widthUsed,
481
+ int parentHeightMeasureSpec,
482
+ int heightUsed) {
483
+ MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
484
+ int childWidthMeasureSpec =
485
+ getChildMeasureSpec(
486
+ parentWidthMeasureSpec,
487
+ parent.getPaddingLeft()
488
+ + parent.getPaddingRight()
489
+ + lp.leftMargin
490
+ + lp.rightMargin
491
+ + widthUsed,
492
+ maxWidth,
493
+ lp.width);
494
+ int childHeightMeasureSpec =
495
+ getChildMeasureSpec(
496
+ parentHeightMeasureSpec,
497
+ parent.getPaddingTop()
498
+ + parent.getPaddingBottom()
499
+ + lp.topMargin
500
+ + lp.bottomMargin
501
+ + heightUsed,
502
+ maxHeight,
503
+ lp.height);
504
+ child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
505
+ return true; // Child was measured
506
+ }
507
+
508
+ private int getChildMeasureSpec(
509
+ int parentMeasureSpec, int padding, int maxSize, int childDimension) {
510
+ int result = ViewGroup.getChildMeasureSpec(parentMeasureSpec, padding, childDimension);
511
+ if (maxSize == NO_MAX_SIZE) {
512
+ return result;
513
+ } else {
514
+ int mode = MeasureSpec.getMode(result);
515
+ int size = MeasureSpec.getSize(result);
516
+ switch (mode) {
517
+ case MeasureSpec.EXACTLY:
518
+ return MeasureSpec.makeMeasureSpec(min(size, maxSize), MeasureSpec.EXACTLY);
519
+ case MeasureSpec.AT_MOST:
520
+ case MeasureSpec.UNSPECIFIED:
521
+ default:
522
+ return MeasureSpec.makeMeasureSpec(
523
+ size == 0 ? maxSize : min(size, maxSize), MeasureSpec.AT_MOST);
524
+ }
525
+ }
526
+ }
527
+
528
+ @Override
529
+ public boolean onLayoutChild(
530
+ @NonNull CoordinatorLayout parent, @NonNull final V child, int layoutDirection) {
531
+ if (ViewCompat.getFitsSystemWindows(parent) && !ViewCompat.getFitsSystemWindows(child)) {
532
+ child.setFitsSystemWindows(true);
533
+ }
534
+
535
+ if (viewRef == null) {
536
+ // First layout with this behavior.
537
+ peekHeightMin =
538
+ parent.getResources().getDimensionPixelSize(R.dimen.design_bottom_sheet_peek_height_min);
539
+ setWindowInsetsListener(child);
540
+ ViewCompat.setWindowInsetsAnimationCallback(child, new InsetsAnimationCallback(child));
541
+ viewRef = new WeakReference<>(child);
542
+ // Only set MaterialShapeDrawable as background if shapeTheming is enabled, otherwise will
543
+ // default to android:background declared in styles or layout.
544
+ if (materialShapeDrawable != null) {
545
+ ViewCompat.setBackground(child, materialShapeDrawable);
546
+ // Use elevation attr if set on bottomsheet; otherwise, use elevation of child view.
547
+ materialShapeDrawable.setElevation(
548
+ elevation == -1 ? ViewCompat.getElevation(child) : elevation);
549
+ } else if (backgroundTint != null) {
550
+ ViewCompat.setBackgroundTintList(child, backgroundTint);
551
+ }
552
+ updateAccessibilityActions();
553
+ if (ViewCompat.getImportantForAccessibility(child)
554
+ == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
555
+ ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
556
+ }
557
+ }
558
+ if (viewDragHelper == null) {
559
+ viewDragHelper = ViewDragHelper.create(parent, dragCallback);
560
+ }
561
+
562
+ int savedTop = child.getTop();
563
+ // First let the parent lay it out
564
+ parent.onLayoutChild(child, layoutDirection);
565
+ // Offset the bottom sheet
566
+ parentWidth = parent.getWidth();
567
+ parentHeight = parent.getHeight();
568
+ childHeight = child.getHeight();
569
+ if (parentHeight - childHeight < insetTop) {
570
+ if (paddingTopSystemWindowInsets) {
571
+ // If the bottomsheet would land in the middle of the status bar when fully expanded add
572
+ // extra space to make sure it goes all the way.
573
+ childHeight = parentHeight;
574
+ } else {
575
+ // If we don't want the bottomsheet to go under the status bar we cap its height
576
+ childHeight = parentHeight - insetTop;
577
+ }
578
+ }
579
+ fitToContentsOffset = max(0, parentHeight - childHeight);
580
+ calculateHalfExpandedOffset();
581
+ calculateCollapsedOffset();
582
+
583
+ if (state == STATE_EXPANDED) {
584
+ ViewCompat.offsetTopAndBottom(child, getExpandedOffset());
585
+ } else if (state == STATE_HALF_EXPANDED) {
586
+ ViewCompat.offsetTopAndBottom(child, halfExpandedOffset);
587
+ } else if (hideable && state == STATE_HIDDEN) {
588
+ ViewCompat.offsetTopAndBottom(child, parentHeight);
589
+ } else if (state == STATE_COLLAPSED) {
590
+ ViewCompat.offsetTopAndBottom(child, collapsedOffset);
591
+ } else if (state == STATE_DRAGGING || state == STATE_SETTLING) {
592
+ ViewCompat.offsetTopAndBottom(child, savedTop - child.getTop());
593
+ }
594
+ updateDrawableForTargetState(state, /* animate= */ false);
595
+
596
+ nestedScrollingChildRef = new WeakReference<>(findScrollingChild(child));
597
+
598
+ for (int i = 0; i < callbacks.size(); i++) {
599
+ callbacks.get(i).onLayout(child);
600
+ }
601
+ return true;
602
+ }
603
+
604
+ @Override
605
+ public boolean onInterceptTouchEvent(
606
+ @NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) {
607
+ if (!child.isShown() || !draggable) {
608
+ ignoreEvents = true;
609
+ return false;
610
+ }
611
+ int action = event.getActionMasked();
612
+ // Record the velocity
613
+ if (action == MotionEvent.ACTION_DOWN) {
614
+ reset();
615
+ }
616
+ if (velocityTracker == null) {
617
+ velocityTracker = VelocityTracker.obtain();
618
+ }
619
+ velocityTracker.addMovement(event);
620
+ switch (action) {
621
+ case MotionEvent.ACTION_UP:
622
+ case MotionEvent.ACTION_CANCEL:
623
+ isHorizontalPanning = false;
624
+ touchingScrollingChild = false;
625
+ activePointerId = MotionEvent.INVALID_POINTER_ID;
626
+ // Reset the ignore flag
627
+ if (ignoreEvents) {
628
+ ignoreEvents = false;
629
+ return false;
630
+ }
631
+ break;
632
+ case MotionEvent.ACTION_MOVE:
633
+ int newX = (int) event.getX();
634
+ int newY = (int) event.getY();
635
+ // panned horizontal
636
+ if (newY - initialY >= 20 && !isHorizontalPanning) {
637
+ ignoreEvents = false;
638
+ } else if (Math.abs(newX - initialX) >= 20) {
639
+ isHorizontalPanning = true;
640
+ ignoreEvents = true;
641
+ }
642
+ break;
643
+ case MotionEvent.ACTION_DOWN:
644
+ isHorizontalPanning = false;
645
+ initialX = (int) event.getX();
646
+ initialY = (int) event.getY();
647
+ // Only intercept nested scrolling events here if the view not being moved by the
648
+ // ViewDragHelper.
649
+ if (state != STATE_SETTLING) {
650
+ View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null;
651
+ if (scroll != null && parent.isPointInChildBounds(scroll, initialX, initialY)) {
652
+ activePointerId = event.getPointerId(event.getActionIndex());
653
+ touchingScrollingChild = true;
654
+ }
655
+ }
656
+ ignoreEvents =
657
+ activePointerId == MotionEvent.INVALID_POINTER_ID
658
+ && !parent.isPointInChildBounds(child, initialX, initialY);
659
+ break;
660
+ default: // fall out
661
+ }
662
+ if (!ignoreEvents
663
+ && viewDragHelper != null
664
+ && viewDragHelper.shouldInterceptTouchEvent(event)) {
665
+ return true;
666
+ }
667
+ // We have to handle cases that the ViewDragHelper does not capture the bottom sheet because
668
+ // it is not the top most view of its parent. This is not necessary when the touch event is
669
+ // happening over the scrolling content as nested scrolling logic handles that case.
670
+ View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null;
671
+ boolean iss = action == MotionEvent.ACTION_MOVE
672
+ && scroll != null
673
+ && !ignoreEvents
674
+ && state != STATE_DRAGGING
675
+ && (!parent.isPointInChildBounds(scroll, (int) event.getX(), (int) event.getY()) || (initialY - event.getY() < 10 && scroll.getScrollY() == 0))
676
+ && viewDragHelper != null
677
+ && Math.abs(initialY - event.getY()) > viewDragHelper.getTouchSlop();
678
+ return iss;
679
+ }
680
+
681
+ @Override
682
+ public boolean onTouchEvent(
683
+ @NonNull CoordinatorLayout parent, @NonNull V child, @NonNull MotionEvent event) {
684
+ if (!child.isShown()) {
685
+ return false;
686
+ }
687
+ int action = event.getActionMasked();
688
+ if (state == STATE_DRAGGING && action == MotionEvent.ACTION_DOWN) {
689
+ return true;
690
+ }
691
+ if (shouldHandleDraggingWithHelper()) {
692
+ viewDragHelper.processTouchEvent(event);
693
+ }
694
+ // Record the velocity
695
+ if (action == MotionEvent.ACTION_DOWN) {
696
+ reset();
697
+ }
698
+ if (velocityTracker == null) {
699
+ velocityTracker = VelocityTracker.obtain();
700
+ }
701
+ velocityTracker.addMovement(event);
702
+ // The ViewDragHelper tries to capture only the top-most View. We have to explicitly tell it
703
+ // to capture the bottom sheet in case it is not captured and the touch slop is passed.
704
+ if (shouldHandleDraggingWithHelper() && action == MotionEvent.ACTION_MOVE && !ignoreEvents) {
705
+ if (Math.abs(initialY - event.getY()) > viewDragHelper.getTouchSlop()) {
706
+ viewDragHelper.captureChildView(child, event.getPointerId(event.getActionIndex()));
707
+ }
708
+ }
709
+ return !ignoreEvents;
710
+ }
711
+
712
+ @Override
713
+ public boolean onStartNestedScroll(
714
+ @NonNull CoordinatorLayout coordinatorLayout,
715
+ @NonNull V child,
716
+ @NonNull View directTargetChild,
717
+ @NonNull View target,
718
+ int axes,
719
+ int type) {
720
+ lastNestedScrollDy = 0;
721
+ nestedScrolled = false;
722
+ return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
723
+ }
724
+
725
+ @Override
726
+ public void onNestedPreScroll(
727
+ @NonNull CoordinatorLayout coordinatorLayout,
728
+ @NonNull V child,
729
+ @NonNull View target,
730
+ int dx,
731
+ int dy,
732
+ @NonNull int[] consumed,
733
+ int type) {
734
+ if (type == ViewCompat.TYPE_NON_TOUCH) {
735
+ // Ignore fling here. The ViewDragHelper handles it.
736
+ return;
737
+ }
738
+ View scrollingChild = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null;
739
+ if (isNestedScrollingCheckEnabled() && target != scrollingChild) {
740
+ return;
741
+ }
742
+ int currentTop = child.getTop();
743
+ int newTop = currentTop - dy;
744
+ if (dy > 0) { // Upward
745
+ if (newTop < getExpandedOffset()) {
746
+ consumed[1] = currentTop - getExpandedOffset();
747
+ ViewCompat.offsetTopAndBottom(child, -consumed[1]);
748
+ setStateInternal(STATE_EXPANDED);
749
+ } else {
750
+ if (!draggable) {
751
+ // Prevent dragging
752
+ return;
753
+ }
754
+
755
+ consumed[1] = dy;
756
+ ViewCompat.offsetTopAndBottom(child, -dy);
757
+ setStateInternal(STATE_DRAGGING);
758
+ }
759
+ } else if (dy < 0) { // Downward
760
+ if (!target.canScrollVertically(-1)) {
761
+ if (newTop <= collapsedOffset || canBeHiddenByDragging()) {
762
+ if (!draggable) {
763
+ // Prevent dragging
764
+ return;
765
+ }
766
+
767
+ consumed[1] = dy;
768
+ ViewCompat.offsetTopAndBottom(child, -dy);
769
+ setStateInternal(STATE_DRAGGING);
770
+ } else {
771
+ consumed[1] = currentTop - collapsedOffset;
772
+ ViewCompat.offsetTopAndBottom(child, -consumed[1]);
773
+ setStateInternal(STATE_COLLAPSED);
774
+ }
775
+ }
776
+ }
777
+ dispatchOnSlide(child.getTop());
778
+ lastNestedScrollDy = dy;
779
+ nestedScrolled = true;
780
+ }
781
+
782
+ @Override
783
+ public void onStopNestedScroll(
784
+ @NonNull CoordinatorLayout coordinatorLayout,
785
+ @NonNull V child,
786
+ @NonNull View target,
787
+ int type) {
788
+ if (child.getTop() == getExpandedOffset()) {
789
+ setStateInternal(STATE_EXPANDED);
790
+ return;
791
+ }
792
+ if (isNestedScrollingCheckEnabled()
793
+ && (nestedScrollingChildRef == null
794
+ || target != nestedScrollingChildRef.get()
795
+ || !nestedScrolled)) {
796
+ return;
797
+ }
798
+ @StableState int targetState;
799
+ if (lastNestedScrollDy > 0) {
800
+ if (fitToContents) {
801
+ targetState = STATE_EXPANDED;
802
+ } else {
803
+ int currentTop = child.getTop();
804
+ if (currentTop > halfExpandedOffset) {
805
+ targetState = STATE_HALF_EXPANDED;
806
+ } else {
807
+ targetState = STATE_EXPANDED;
808
+ }
809
+ }
810
+ } else if (hideable && shouldHide(child, getYVelocity())) {
811
+ targetState = STATE_HIDDEN;
812
+ } else if (lastNestedScrollDy == 0) {
813
+ int currentTop = child.getTop();
814
+ if (fitToContents) {
815
+ if (Math.abs(currentTop - fitToContentsOffset) < Math.abs(currentTop - collapsedOffset)) {
816
+ targetState = STATE_EXPANDED;
817
+ } else {
818
+ targetState = STATE_COLLAPSED;
819
+ }
820
+ } else {
821
+ if (currentTop < halfExpandedOffset) {
822
+ if (currentTop < Math.abs(currentTop - collapsedOffset)) {
823
+ targetState = STATE_EXPANDED;
824
+ } else {
825
+ if (shouldSkipHalfExpandedStateWhenDragging()) {
826
+ targetState = STATE_COLLAPSED;
827
+ } else {
828
+ targetState = STATE_HALF_EXPANDED;
829
+ }
830
+ }
831
+ } else {
832
+ if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) {
833
+ targetState = STATE_HALF_EXPANDED;
834
+ } else {
835
+ targetState = STATE_COLLAPSED;
836
+ }
837
+ }
838
+ }
839
+ } else {
840
+ if (fitToContents) {
841
+ targetState = STATE_COLLAPSED;
842
+ } else {
843
+ // Settle to nearest height.
844
+ int currentTop = child.getTop();
845
+ if (Math.abs(currentTop - halfExpandedOffset) < Math.abs(currentTop - collapsedOffset)) {
846
+ targetState = STATE_HALF_EXPANDED;
847
+ } else {
848
+ targetState = STATE_COLLAPSED;
849
+ }
850
+ }
851
+ }
852
+ startSettling(child, targetState, false);
853
+ nestedScrolled = false;
854
+ }
855
+
856
+ @Override
857
+ public void onNestedScroll(
858
+ @NonNull CoordinatorLayout coordinatorLayout,
859
+ @NonNull V child,
860
+ @NonNull View target,
861
+ int dxConsumed,
862
+ int dyConsumed,
863
+ int dxUnconsumed,
864
+ int dyUnconsumed,
865
+ int type,
866
+ @NonNull int[] consumed) {
867
+ // Overridden to prevent the default consumption of the entire scroll distance.
868
+ }
869
+
870
+ @Override
871
+ public boolean onNestedPreFling(
872
+ @NonNull CoordinatorLayout coordinatorLayout,
873
+ @NonNull V child,
874
+ @NonNull View target,
875
+ float velocityX,
876
+ float velocityY) {
877
+
878
+ if (isNestedScrollingCheckEnabled() && nestedScrollingChildRef != null) {
879
+ return target == nestedScrollingChildRef.get()
880
+ && (state != STATE_EXPANDED
881
+ || super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY));
882
+ } else {
883
+ return false;
884
+ }
885
+ }
886
+
887
+ /**
888
+ * @return whether the height of the expanded sheet is determined by the height of its contents,
889
+ * or if it is expanded in two stages (half the height of the parent container, full height of
890
+ * parent container).
891
+ */
892
+ public boolean isFitToContents() {
893
+ return fitToContents;
894
+ }
895
+
896
+ /**
897
+ * Sets whether the height of the expanded sheet is determined by the height of its contents, or
898
+ * if it is expanded in two stages (half the height of the parent container, full height of parent
899
+ * container). Default value is true.
900
+ *
901
+ * @param fitToContents whether or not to fit the expanded sheet to its contents.
902
+ */
903
+ public void setFitToContents(boolean fitToContents) {
904
+ if (this.fitToContents == fitToContents) {
905
+ return;
906
+ }
907
+ this.fitToContents = fitToContents;
908
+
909
+ // If sheet is already laid out, recalculate the collapsed offset based on new setting.
910
+ // Otherwise, let onLayoutChild handle this later.
911
+ if (viewRef != null) {
912
+ calculateCollapsedOffset();
913
+ }
914
+ // Fix incorrect expanded settings depending on whether or not we are fitting sheet to contents.
915
+ setStateInternal((this.fitToContents && state == STATE_HALF_EXPANDED) ? STATE_EXPANDED : state);
916
+
917
+ updateDrawableForTargetState(state, /* animate= */ true);
918
+ updateAccessibilityActions();
919
+ }
920
+
921
+ /**
922
+ * Sets the maximum width of the bottom sheet. The layout will be at most this dimension wide.
923
+ * This method should be called before {@link BottomSheetDialog#show()} in order for the width to
924
+ * be adjusted as expected.
925
+ *
926
+ * @param maxWidth The maximum width in pixels to be set
927
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_android_maxWidth
928
+ * @see #getMaxWidth()
929
+ */
930
+ public void setMaxWidth(@Px int maxWidth) {
931
+ this.maxWidth = maxWidth;
932
+ }
933
+
934
+ /**
935
+ * Returns the bottom sheet's maximum width, or -1 if no maximum width is set.
936
+ *
937
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_android_maxWidth
938
+ * @see #setMaxWidth(int)
939
+ */
940
+ @Px
941
+ public int getMaxWidth() {
942
+ return maxWidth;
943
+ }
944
+
945
+ /**
946
+ * Sets the maximum height of the bottom sheet. This method should be called before {@link
947
+ * BottomSheetDialog#show()} in order for the height to be adjusted as expected.
948
+ *
949
+ * @param maxHeight The maximum height in pixels to be set
950
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_android_maxHeight
951
+ * @see #getMaxHeight()
952
+ */
953
+ public void setMaxHeight(@Px int maxHeight) {
954
+ this.maxHeight = maxHeight;
955
+ }
956
+
957
+ /**
958
+ * Returns the bottom sheet's maximum height, or -1 if no maximum height is set.
959
+ *
960
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_android_maxHeight
961
+ * @see #setMaxHeight(int)
962
+ */
963
+ @Px
964
+ public int getMaxHeight() {
965
+ return maxHeight;
966
+ }
967
+
968
+ /**
969
+ * Sets the height of the bottom sheet when it is collapsed.
970
+ *
971
+ * @param peekHeight The height of the collapsed bottom sheet in pixels, or {@link
972
+ * #PEEK_HEIGHT_AUTO} to configure the sheet to peek automatically at 16:9 ratio keyline.
973
+ * @attr ref
974
+ * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight
975
+ */
976
+ public void setPeekHeight(int peekHeight) {
977
+ setPeekHeight(peekHeight, false);
978
+ }
979
+
980
+ /**
981
+ * Sets the height of the bottom sheet when it is collapsed while optionally animating between the
982
+ * old height and the new height.
983
+ *
984
+ * @param peekHeight The height of the collapsed bottom sheet in pixels, or {@link
985
+ * #PEEK_HEIGHT_AUTO} to configure the sheet to peek automatically at 16:9 ratio keyline.
986
+ * @param animate Whether to animate between the old height and the new height.
987
+ * @attr ref
988
+ * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight
989
+ */
990
+ public final void setPeekHeight(int peekHeight, boolean animate) {
991
+ boolean layout = false;
992
+ if (peekHeight == PEEK_HEIGHT_AUTO) {
993
+ if (!peekHeightAuto) {
994
+ peekHeightAuto = true;
995
+ layout = true;
996
+ }
997
+ } else if (peekHeightAuto || this.peekHeight != peekHeight) {
998
+ peekHeightAuto = false;
999
+ this.peekHeight = max(0, peekHeight);
1000
+ layout = true;
1001
+ }
1002
+ // If sheet is already laid out, recalculate the collapsed offset based on new setting.
1003
+ // Otherwise, let onLayoutChild handle this later.
1004
+ if (layout) {
1005
+ updatePeekHeight(animate);
1006
+ }
1007
+ }
1008
+
1009
+ private void updatePeekHeight(boolean animate) {
1010
+ if (viewRef != null) {
1011
+ calculateCollapsedOffset();
1012
+ if (state == STATE_COLLAPSED) {
1013
+ V view = viewRef.get();
1014
+ if (view != null) {
1015
+ if (animate) {
1016
+ setState(STATE_COLLAPSED);
1017
+ } else {
1018
+ view.requestLayout();
1019
+ }
1020
+ }
1021
+ }
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * Gets the height of the bottom sheet when it is collapsed.
1027
+ *
1028
+ * @return The height of the collapsed bottom sheet in pixels, or {@link #PEEK_HEIGHT_AUTO} if the
1029
+ * sheet is configured to peek automatically at 16:9 ratio keyline
1030
+ * @attr ref
1031
+ * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_peekHeight
1032
+ */
1033
+ public int getPeekHeight() {
1034
+ return peekHeightAuto ? PEEK_HEIGHT_AUTO : peekHeight;
1035
+ }
1036
+
1037
+ /**
1038
+ * Determines the height of the BottomSheet in the {@link #STATE_HALF_EXPANDED} state. The
1039
+ * material guidelines recommended a value of 0.5, which results in the sheet filling half of the
1040
+ * parent. The height of the BottomSheet will be smaller as this ratio is decreased and taller as
1041
+ * it is increased. The default value is 0.5.
1042
+ *
1043
+ * @param ratio a float between 0 and 1, representing the {@link #STATE_HALF_EXPANDED} ratio.
1044
+ * @attr ref
1045
+ * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_halfExpandedRatio
1046
+ */
1047
+ public void setHalfExpandedRatio(
1048
+ @FloatRange(from = 0.0f, to = 1.0f, fromInclusive = false, toInclusive = false) float ratio) {
1049
+
1050
+ if ((ratio <= 0) || (ratio >= 1)) {
1051
+ throw new IllegalArgumentException("ratio must be a float value between 0 and 1");
1052
+ }
1053
+ this.halfExpandedRatio = ratio;
1054
+ // If sheet is already laid out, recalculate the half expanded offset based on new setting.
1055
+ // Otherwise, let onLayoutChild handle this later.
1056
+ if (viewRef != null) {
1057
+ calculateHalfExpandedOffset();
1058
+ }
1059
+ }
1060
+
1061
+ /**
1062
+ * Gets the ratio for the height of the BottomSheet in the {@link #STATE_HALF_EXPANDED} state.
1063
+ *
1064
+ * @attr ref
1065
+ * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_halfExpandedRatio
1066
+ */
1067
+ @FloatRange(from = 0.0f, to = 1.0f)
1068
+ public float getHalfExpandedRatio() {
1069
+ return halfExpandedRatio;
1070
+ }
1071
+
1072
+ /**
1073
+ * Determines the top offset of the BottomSheet in the {@link #STATE_EXPANDED} state when
1074
+ * fitsToContent is false. The default value is 0, which results in the sheet matching the
1075
+ * parent's top.
1076
+ *
1077
+ * @param offset an integer value greater than equal to 0, representing the {@link
1078
+ * #STATE_EXPANDED} offset. Value must not exceed the offset in the half expanded state.
1079
+ * @attr ref
1080
+ * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_expandedOffset
1081
+ */
1082
+ public void setExpandedOffset(int offset) {
1083
+ if (offset < 0) {
1084
+ throw new IllegalArgumentException("offset must be greater than or equal to 0");
1085
+ }
1086
+ this.expandedOffset = offset;
1087
+ updateDrawableForTargetState(state, /* animate= */ true);
1088
+ }
1089
+
1090
+ /**
1091
+ * Returns the current expanded offset. If {@code fitToContents} is true, it will automatically
1092
+ * pick the offset depending on the height of the content.
1093
+ *
1094
+ * @attr ref
1095
+ * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_expandedOffset
1096
+ */
1097
+ public int getExpandedOffset() {
1098
+ return fitToContents
1099
+ ? fitToContentsOffset
1100
+ : Math.max(expandedOffset, paddingTopSystemWindowInsets ? 0 : insetTop);
1101
+ }
1102
+
1103
+ /**
1104
+ * Calculates the current offset of the bottom sheet.
1105
+ *
1106
+ * This method should be called when the child view is laid out.
1107
+ *
1108
+ * @return The offset of this bottom sheet within [-1,1] range. Offset increases
1109
+ * as this bottom sheet is moving upward. From 0 to 1 the sheet is between collapsed and
1110
+ * expanded states and from -1 to 0 it is between hidden and collapsed states. Returns
1111
+ * -1 if the bottom sheet is not laid out (therefore it's hidden).
1112
+ */
1113
+ public float calculateSlideOffset() {
1114
+ if (viewRef == null || viewRef.get() == null) {
1115
+ return -1;
1116
+ }
1117
+
1118
+ return calculateSlideOffsetWithTop(viewRef.get().getTop());
1119
+ }
1120
+
1121
+ /**
1122
+ * Sets whether this bottom sheet can hide.
1123
+ *
1124
+ * @param hideable {@code true} to make this bottom sheet hideable.
1125
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_hideable
1126
+ */
1127
+ public void setHideable(boolean hideable) {
1128
+ if (this.hideable != hideable) {
1129
+ this.hideable = hideable;
1130
+ if (!hideable && state == STATE_HIDDEN) {
1131
+ // Lift up to collapsed state
1132
+ setState(STATE_COLLAPSED);
1133
+ }
1134
+ updateAccessibilityActions();
1135
+ }
1136
+ }
1137
+
1138
+ /**
1139
+ * Gets whether this bottom sheet can hide when it is swiped down.
1140
+ *
1141
+ * @return {@code true} if this bottom sheet can hide.
1142
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_hideable
1143
+ */
1144
+ public boolean isHideable() {
1145
+ return hideable;
1146
+ }
1147
+
1148
+ /**
1149
+ * Sets whether this bottom sheet should skip the collapsed state when it is being hidden after it
1150
+ * is expanded once. Setting this to true has no effect unless the sheet is hideable.
1151
+ *
1152
+ * @param skipCollapsed True if the bottom sheet should skip the collapsed state.
1153
+ * @attr ref
1154
+ * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_skipCollapsed
1155
+ */
1156
+ public void setSkipCollapsed(boolean skipCollapsed) {
1157
+ this.skipCollapsed = skipCollapsed;
1158
+ }
1159
+
1160
+ /**
1161
+ * Sets whether this bottom sheet should skip the collapsed state when it is being hidden after it
1162
+ * is expanded once.
1163
+ *
1164
+ * @return Whether the bottom sheet should skip the collapsed state.
1165
+ * @attr ref
1166
+ * com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_skipCollapsed
1167
+ */
1168
+ public boolean getSkipCollapsed() {
1169
+ return skipCollapsed;
1170
+ }
1171
+
1172
+ /**
1173
+ * Sets whether this bottom sheet is can be collapsed/expanded by dragging. Note: When disabling
1174
+ * dragging, an app will require to implement a custom way to expand/collapse the bottom sheet
1175
+ *
1176
+ * @param draggable {@code false} to prevent dragging the sheet to collapse and expand
1177
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_draggable
1178
+ */
1179
+ public void setDraggable(boolean draggable) {
1180
+ this.draggable = draggable;
1181
+ }
1182
+
1183
+ public boolean isDraggable() {
1184
+ return draggable;
1185
+ }
1186
+
1187
+ /*
1188
+ * Sets the velocity threshold considered significant enough to trigger a slide
1189
+ * to the next stable state.
1190
+ *
1191
+ * @param significantVelocityThreshold The velocity threshold that warrants a vertical swipe.
1192
+ * @see #getSignificantVelocityThreshold()
1193
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_significantVelocityThreshold
1194
+ */
1195
+ public void setSignificantVelocityThreshold(int significantVelocityThreshold) {
1196
+ this.significantVelocityThreshold = significantVelocityThreshold;
1197
+ }
1198
+
1199
+ /*
1200
+ * Returns the significant velocity threshold.
1201
+ *
1202
+ * @see #setSignificantVelocityThreshold(int)
1203
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_significantVelocityThreshold
1204
+ */
1205
+ public int getSignificantVelocityThreshold() {
1206
+ return this.significantVelocityThreshold;
1207
+ }
1208
+
1209
+ /**
1210
+ * Sets save flags to be preserved in bottomsheet on configuration change.
1211
+ *
1212
+ * @param flags bitwise int of {@link #SAVE_PEEK_HEIGHT}, {@link #SAVE_FIT_TO_CONTENTS}, {@link
1213
+ * #SAVE_HIDEABLE}, {@link #SAVE_SKIP_COLLAPSED}, {@link #SAVE_ALL} and {@link #SAVE_NONE}.
1214
+ * @see #getSaveFlags()
1215
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_saveFlags
1216
+ */
1217
+ public void setSaveFlags(@SaveFlags int flags) {
1218
+ this.saveFlags = flags;
1219
+ }
1220
+ /**
1221
+ * Returns the save flags.
1222
+ *
1223
+ * @see #setSaveFlags(int)
1224
+ * @attr ref com.google.android.material.R.styleable#BottomSheetBehavior_Layout_behavior_saveFlags
1225
+ */
1226
+ @SaveFlags
1227
+ public int getSaveFlags() {
1228
+ return this.saveFlags;
1229
+ }
1230
+
1231
+ /**
1232
+ * Sets the friction coefficient to hide the bottom sheet, or set it to the next closest
1233
+ * expanded state.
1234
+ *
1235
+ * @param hideFriction The friction coefficient that determines the swipe velocity needed to
1236
+ * hide or set the bottom sheet to the closest expanded state.
1237
+ */
1238
+ public void setHideFriction(float hideFriction) {
1239
+ this.hideFriction = hideFriction;
1240
+ }
1241
+
1242
+ /**
1243
+ * Gets the friction coefficient to hide the bottom sheet, or set it to the next closest
1244
+ * expanded state.
1245
+ *
1246
+ * @return The friction coefficient that determines the swipe velocity needed to hide or set the
1247
+ * bottom sheet to the closest expanded state.
1248
+ */
1249
+ public float getHideFriction() {
1250
+ return this.hideFriction;
1251
+ }
1252
+
1253
+ /**
1254
+ * Sets a callback to be notified of bottom sheet events.
1255
+ *
1256
+ * @param callback The callback to notify when bottom sheet events occur.
1257
+ * @deprecated use {@link #addBottomSheetCallback(BottomSheetCallback)} and {@link
1258
+ * #removeBottomSheetCallback(BottomSheetCallback)} instead
1259
+ */
1260
+ @Deprecated
1261
+ public void setBottomSheetCallback(BottomSheetCallback callback) {
1262
+ Log.w(
1263
+ TAG,
1264
+ "BottomSheetBehavior now supports multiple callbacks. `setBottomSheetCallback()` removes"
1265
+ + " all existing callbacks, including ones set internally by library authors, which"
1266
+ + " may result in unintended behavior. This may change in the future. Please use"
1267
+ + " `addBottomSheetCallback()` and `removeBottomSheetCallback()` instead to set your"
1268
+ + " own callbacks.");
1269
+ callbacks.clear();
1270
+ if (callback != null) {
1271
+ callbacks.add(callback);
1272
+ }
1273
+ }
1274
+
1275
+ /**
1276
+ * Adds a callback to be notified of bottom sheet events.
1277
+ *
1278
+ * @param callback The callback to notify when bottom sheet events occur.
1279
+ */
1280
+ public void addBottomSheetCallback(@NonNull BottomSheetCallback callback) {
1281
+ if (!callbacks.contains(callback)) {
1282
+ callbacks.add(callback);
1283
+ }
1284
+ }
1285
+
1286
+ /**
1287
+ * Removes a previously added callback.
1288
+ *
1289
+ * @param callback The callback to remove.
1290
+ */
1291
+ public void removeBottomSheetCallback(@NonNull BottomSheetCallback callback) {
1292
+ callbacks.remove(callback);
1293
+ }
1294
+
1295
+ /**
1296
+ * Sets the state of the bottom sheet. The bottom sheet will transition to that state with
1297
+ * animation.
1298
+ *
1299
+ * @param state One of {@link #STATE_COLLAPSED}, {@link #STATE_EXPANDED}, {@link #STATE_HIDDEN},
1300
+ * or {@link #STATE_HALF_EXPANDED}.
1301
+ */
1302
+ public void setState(@StableState int state) {
1303
+ if (state == STATE_DRAGGING || state == STATE_SETTLING) {
1304
+ throw new IllegalArgumentException(
1305
+ "STATE_"
1306
+ + (state == STATE_DRAGGING ? "DRAGGING" : "SETTLING")
1307
+ + " should not be set externally.");
1308
+ }
1309
+ if (!hideable && state == STATE_HIDDEN) {
1310
+ Log.w(TAG, "Cannot set state: " + state);
1311
+ return;
1312
+ }
1313
+ final int finalState;
1314
+ if (state == STATE_HALF_EXPANDED
1315
+ && fitToContents
1316
+ && getTopOffsetForState(state) <= fitToContentsOffset) {
1317
+ // Skip to the expanded state if we would scroll past the height of the contents.
1318
+ finalState = STATE_EXPANDED;
1319
+ } else {
1320
+ finalState = state;
1321
+ }
1322
+ if (viewRef == null || viewRef.get() == null) {
1323
+ // The view is not laid out yet; modify mState and let onLayoutChild handle it later
1324
+ setStateInternal(state);
1325
+ } else {
1326
+ final V child = viewRef.get();
1327
+ runAfterLayout(
1328
+ child,
1329
+ new Runnable() {
1330
+ @Override
1331
+ public void run() {
1332
+ startSettling(child, finalState, false);
1333
+ }
1334
+ });
1335
+ }
1336
+ }
1337
+
1338
+ private void runAfterLayout(V child, Runnable runnable) {
1339
+ if (isLayouting(child)) {
1340
+ child.post(runnable);
1341
+ } else {
1342
+ runnable.run();
1343
+ }
1344
+ }
1345
+
1346
+ private boolean isLayouting(V child) {
1347
+ ViewParent parent = child.getParent();
1348
+ return parent != null && parent.isLayoutRequested() && ViewCompat.isAttachedToWindow(child);
1349
+ }
1350
+
1351
+ /**
1352
+ * Sets whether this bottom sheet should adjust it's position based on the system gesture area on
1353
+ * Android Q and above.
1354
+ *
1355
+ * <p>Note: the bottom sheet will only adjust it's position if it would be unable to be scrolled
1356
+ * upwards because the peekHeight is less than the gesture inset margins,(because that would cause
1357
+ * a gesture conflict), gesture navigation is enabled, and this {@code ignoreGestureInsetBottom}
1358
+ * flag is false.
1359
+ */
1360
+ public void setGestureInsetBottomIgnored(boolean gestureInsetBottomIgnored) {
1361
+ this.gestureInsetBottomIgnored = gestureInsetBottomIgnored;
1362
+ }
1363
+
1364
+ /**
1365
+ * Returns whether this bottom sheet should adjust it's position based on the system gesture area.
1366
+ */
1367
+ public boolean isGestureInsetBottomIgnored() {
1368
+ return gestureInsetBottomIgnored;
1369
+ }
1370
+
1371
+ /**
1372
+ * Gets the current state of the bottom sheet.
1373
+ *
1374
+ * @return One of {@link #STATE_EXPANDED}, {@link #STATE_HALF_EXPANDED}, {@link #STATE_COLLAPSED},
1375
+ * {@link #STATE_DRAGGING}, or {@link #STATE_SETTLING}.
1376
+ */
1377
+ @State
1378
+ public int getState() {
1379
+ return state;
1380
+ }
1381
+
1382
+ void setStateInternal(@State int state) {
1383
+ if (this.state == state) {
1384
+ return;
1385
+ }
1386
+ this.state = state;
1387
+ if (state == STATE_COLLAPSED
1388
+ || state == STATE_EXPANDED
1389
+ || state == STATE_HALF_EXPANDED
1390
+ || (hideable && state == STATE_HIDDEN)) {
1391
+ this.lastStableState = state;
1392
+ }
1393
+
1394
+ if (viewRef == null) {
1395
+ return;
1396
+ }
1397
+
1398
+ View bottomSheet = viewRef.get();
1399
+ if (bottomSheet == null) {
1400
+ return;
1401
+ }
1402
+
1403
+ if (state == STATE_EXPANDED) {
1404
+ updateImportantForAccessibility(true);
1405
+ } else if (state == STATE_HALF_EXPANDED || state == STATE_HIDDEN || state == STATE_COLLAPSED) {
1406
+ updateImportantForAccessibility(false);
1407
+ }
1408
+
1409
+ updateDrawableForTargetState(state, /* animate= */ true);
1410
+ for (int i = 0; i < callbacks.size(); i++) {
1411
+ callbacks.get(i).onStateChanged(bottomSheet, state);
1412
+ }
1413
+ updateAccessibilityActions();
1414
+ }
1415
+
1416
+ private void updateDrawableForTargetState(@State int state, boolean animate) {
1417
+ if (state == STATE_SETTLING) {
1418
+ // Special case: we want to know which state we're settling to, so wait for another call.
1419
+ return;
1420
+ }
1421
+
1422
+ boolean removeCorners = isExpandedAndShouldRemoveCorners();
1423
+ if (expandedCornersRemoved == removeCorners || materialShapeDrawable == null) {
1424
+ return;
1425
+ }
1426
+ expandedCornersRemoved = removeCorners;
1427
+ if (animate && interpolatorAnimator != null) {
1428
+ if (interpolatorAnimator.isRunning()) {
1429
+ interpolatorAnimator.reverse();
1430
+ } else {
1431
+ float to = removeCorners ? 0f : 1f;
1432
+ float from = 1f - to;
1433
+ interpolatorAnimator.setFloatValues(from, to);
1434
+ interpolatorAnimator.start();
1435
+ }
1436
+ } else {
1437
+ if (interpolatorAnimator != null && interpolatorAnimator.isRunning()) {
1438
+ interpolatorAnimator.cancel();
1439
+ }
1440
+ materialShapeDrawable.setInterpolation(expandedCornersRemoved ? 0f : 1f);
1441
+ }
1442
+ }
1443
+
1444
+ private boolean isExpandedAndShouldRemoveCorners() {
1445
+ // Only remove corners when it's full screen.
1446
+ return state == STATE_EXPANDED && (shouldRemoveExpandedCorners || getExpandedOffset() == 0);
1447
+ }
1448
+
1449
+ private int calculatePeekHeight() {
1450
+ if (peekHeightAuto) {
1451
+ int desiredHeight = max(peekHeightMin, parentHeight - parentWidth * 9 / 16);
1452
+ return min(desiredHeight, childHeight) + insetBottom;
1453
+ }
1454
+ // Only make sure the peek height is above the gesture insets if we're not applying system
1455
+ // insets.
1456
+ if (!gestureInsetBottomIgnored && !paddingBottomSystemWindowInsets && gestureInsetBottom > 0) {
1457
+ return max(peekHeight, gestureInsetBottom + peekHeightGestureInsetBuffer);
1458
+ }
1459
+ return peekHeight + insetBottom;
1460
+ }
1461
+
1462
+ private void calculateCollapsedOffset() {
1463
+ int peek = calculatePeekHeight();
1464
+
1465
+ if (fitToContents) {
1466
+ collapsedOffset = max(parentHeight - peek, fitToContentsOffset);
1467
+ } else {
1468
+ collapsedOffset = parentHeight - peek;
1469
+ }
1470
+ }
1471
+
1472
+ private void calculateHalfExpandedOffset() {
1473
+ this.halfExpandedOffset = (int) (parentHeight * (1 - halfExpandedRatio));
1474
+ }
1475
+
1476
+ private float calculateSlideOffsetWithTop(int top) {
1477
+ return
1478
+ (top > collapsedOffset || collapsedOffset == getExpandedOffset())
1479
+ ? (float) (collapsedOffset - top) / (parentHeight - collapsedOffset)
1480
+ : (float) (collapsedOffset - top) / (collapsedOffset - getExpandedOffset());
1481
+ }
1482
+
1483
+ private void reset() {
1484
+ activePointerId = ViewDragHelper.INVALID_POINTER;
1485
+ if (velocityTracker != null) {
1486
+ velocityTracker.recycle();
1487
+ velocityTracker = null;
1488
+ }
1489
+ }
1490
+
1491
+ private void restoreOptionalState(@NonNull SavedState ss) {
1492
+ if (this.saveFlags == SAVE_NONE) {
1493
+ return;
1494
+ }
1495
+ if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_PEEK_HEIGHT) == SAVE_PEEK_HEIGHT) {
1496
+ this.peekHeight = ss.peekHeight;
1497
+ }
1498
+ if (this.saveFlags == SAVE_ALL
1499
+ || (this.saveFlags & SAVE_FIT_TO_CONTENTS) == SAVE_FIT_TO_CONTENTS) {
1500
+ this.fitToContents = ss.fitToContents;
1501
+ }
1502
+ if (this.saveFlags == SAVE_ALL || (this.saveFlags & SAVE_HIDEABLE) == SAVE_HIDEABLE) {
1503
+ this.hideable = ss.hideable;
1504
+ }
1505
+ if (this.saveFlags == SAVE_ALL
1506
+ || (this.saveFlags & SAVE_SKIP_COLLAPSED) == SAVE_SKIP_COLLAPSED) {
1507
+ this.skipCollapsed = ss.skipCollapsed;
1508
+ }
1509
+ }
1510
+
1511
+ boolean shouldHide(@NonNull View child, float yvel) {
1512
+ if (skipCollapsed) {
1513
+ return true;
1514
+ }
1515
+ if (!isHideableWhenDragging()) {
1516
+ return false;
1517
+ }
1518
+ if (child.getTop() < collapsedOffset) {
1519
+ // It should not hide, but collapse.
1520
+ return false;
1521
+ }
1522
+ int peek = calculatePeekHeight();
1523
+ final float newTop = child.getTop() + yvel * hideFriction;
1524
+ return Math.abs(newTop - collapsedOffset) / (float) peek > HIDE_THRESHOLD;
1525
+ }
1526
+
1527
+ @Nullable
1528
+ @VisibleForTesting
1529
+ View findScrollingChild(View view) {
1530
+ View fittedSheetScrollView = findView(view, "fittedSheetScrollView");
1531
+ if (fittedSheetScrollView == null) return null;
1532
+ fittedSheetScrollView.setNestedScrollingEnabled(true);
1533
+ return fittedSheetScrollView;
1534
+ // if (view.getVisibility() != View.VISIBLE) {
1535
+ // return null;
1536
+ // }
1537
+ // if (ViewCompat.isNestedScrollingEnabled(view)) {
1538
+ // return view;
1539
+ // }
1540
+ // if (view instanceof ViewGroup) {
1541
+ // ViewGroup group = (ViewGroup) view;
1542
+ // for (int i = 0, count = group.getChildCount(); i < count; i++) {
1543
+ // View scrollingChild = findScrollingChild(group.getChildAt(i));
1544
+ // if (scrollingChild != null) {
1545
+ // return scrollingChild;
1546
+ // }
1547
+ // }
1548
+ // }
1549
+ // return null;
1550
+ }
1551
+
1552
+ private boolean shouldHandleDraggingWithHelper() {
1553
+ // If it's not draggable, do not forward events to viewDragHelper; however, if it's already
1554
+ // dragging, let it finish.
1555
+ return viewDragHelper != null && (draggable || state == STATE_DRAGGING);
1556
+ }
1557
+
1558
+ private void createMaterialShapeDrawableIfNeeded(@NonNull Context context) {
1559
+ if (shapeAppearanceModelDefault == null) {
1560
+ return;
1561
+ }
1562
+
1563
+ this.materialShapeDrawable = new MaterialShapeDrawable(shapeAppearanceModelDefault);
1564
+ this.materialShapeDrawable.initializeElevationOverlay(context);
1565
+
1566
+ if (backgroundTint != null) {
1567
+ materialShapeDrawable.setFillColor(backgroundTint);
1568
+ } else {
1569
+ // If the tint isn't set, use the theme default background color.
1570
+ TypedValue defaultColor = new TypedValue();
1571
+ context.getTheme().resolveAttribute(android.R.attr.colorBackground, defaultColor, true);
1572
+ materialShapeDrawable.setTint(defaultColor.data);
1573
+ }
1574
+ }
1575
+
1576
+ MaterialShapeDrawable getMaterialShapeDrawable() {
1577
+ return materialShapeDrawable;
1578
+ }
1579
+
1580
+ private void createShapeValueAnimator() {
1581
+ interpolatorAnimator = ValueAnimator.ofFloat(0f, 1f);
1582
+ interpolatorAnimator.setDuration(CORNER_ANIMATION_DURATION);
1583
+ interpolatorAnimator.addUpdateListener(
1584
+ new AnimatorUpdateListener() {
1585
+ @Override
1586
+ public void onAnimationUpdate(@NonNull ValueAnimator animation) {
1587
+ float value = (float) animation.getAnimatedValue();
1588
+ if (materialShapeDrawable != null) {
1589
+ materialShapeDrawable.setInterpolation(value);
1590
+ }
1591
+ }
1592
+ });
1593
+ }
1594
+
1595
+ private void setWindowInsetsListener(@NonNull View child) {
1596
+ // Ensure the peek height is at least as large as the bottom gesture inset size so that
1597
+ // the sheet can always be dragged, but only when the inset is required by the system.
1598
+ final boolean shouldHandleGestureInsets =
1599
+ VERSION.SDK_INT >= VERSION_CODES.Q && !isGestureInsetBottomIgnored() && !peekHeightAuto;
1600
+
1601
+ // If were not handling insets at all, don't apply the listener.
1602
+ if (!paddingBottomSystemWindowInsets
1603
+ && !paddingLeftSystemWindowInsets
1604
+ && !paddingRightSystemWindowInsets
1605
+ && !marginLeftSystemWindowInsets
1606
+ && !marginRightSystemWindowInsets
1607
+ && !marginTopSystemWindowInsets
1608
+ && !shouldHandleGestureInsets) {
1609
+ return;
1610
+ }
1611
+ ViewUtils.doOnApplyWindowInsets(
1612
+ child,
1613
+ new ViewUtils.OnApplyWindowInsetsListener() {
1614
+ @Override
1615
+ @SuppressWarnings("deprecation") // getSystemWindowInsetBottom is used for adjustResize.
1616
+ public WindowInsetsCompat onApplyWindowInsets(
1617
+ View view, WindowInsetsCompat insets, RelativePadding initialPadding) {
1618
+ Insets systemBarInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars());
1619
+ Insets mandatoryGestureInsets =
1620
+ insets.getInsets(WindowInsetsCompat.Type.mandatorySystemGestures());
1621
+
1622
+ insetTop = systemBarInsets.top;
1623
+
1624
+ boolean isRtl = ViewUtils.isLayoutRtl(view);
1625
+
1626
+ int bottomPadding = view.getPaddingBottom();
1627
+ int leftPadding = view.getPaddingLeft();
1628
+ int rightPadding = view.getPaddingRight();
1629
+
1630
+ if (paddingBottomSystemWindowInsets) {
1631
+ // Intentionally uses getSystemWindowInsetBottom to apply padding properly when
1632
+ // adjustResize is used as the windowSoftInputMode.
1633
+ insetBottom = insets.getSystemWindowInsetBottom();
1634
+ bottomPadding = initialPadding.bottom + insetBottom;
1635
+ }
1636
+
1637
+ if (paddingLeftSystemWindowInsets) {
1638
+ leftPadding = isRtl ? initialPadding.end : initialPadding.start;
1639
+ leftPadding += systemBarInsets.left;
1640
+ }
1641
+
1642
+ if (paddingRightSystemWindowInsets) {
1643
+ rightPadding = isRtl ? initialPadding.start : initialPadding.end;
1644
+ rightPadding += systemBarInsets.right;
1645
+ }
1646
+
1647
+ MarginLayoutParams mlp = (MarginLayoutParams) view.getLayoutParams();
1648
+ boolean marginUpdated = false;
1649
+
1650
+ if (marginLeftSystemWindowInsets && mlp.leftMargin != systemBarInsets.left) {
1651
+ mlp.leftMargin = systemBarInsets.left;
1652
+ marginUpdated = true;
1653
+ }
1654
+
1655
+ if (marginRightSystemWindowInsets && mlp.rightMargin != systemBarInsets.right) {
1656
+ mlp.rightMargin = systemBarInsets.right;
1657
+ marginUpdated = true;
1658
+ }
1659
+
1660
+ if (marginTopSystemWindowInsets && mlp.topMargin != systemBarInsets.top) {
1661
+ mlp.topMargin = systemBarInsets.top;
1662
+ marginUpdated = true;
1663
+ }
1664
+
1665
+ if (marginUpdated) {
1666
+ view.setLayoutParams(mlp);
1667
+ }
1668
+ view.setPadding(leftPadding, view.getPaddingTop(), rightPadding, bottomPadding);
1669
+
1670
+ if (shouldHandleGestureInsets) {
1671
+ gestureInsetBottom = mandatoryGestureInsets.bottom;
1672
+ }
1673
+
1674
+ // Don't update the peek height to be above the navigation bar or gestures if these
1675
+ // flags are off. It means the client is already handling it.
1676
+ if (paddingBottomSystemWindowInsets || shouldHandleGestureInsets) {
1677
+ updatePeekHeight(/* animate= */ false);
1678
+ }
1679
+ return insets;
1680
+ }
1681
+ });
1682
+ }
1683
+
1684
+ private float getYVelocity() {
1685
+ if (velocityTracker == null) {
1686
+ return 0;
1687
+ }
1688
+ velocityTracker.computeCurrentVelocity(1000, maximumVelocity);
1689
+ return velocityTracker.getYVelocity(activePointerId);
1690
+ }
1691
+
1692
+ private void startSettling(View child, @StableState int state, boolean isReleasingView) {
1693
+ int top = getTopOffsetForState(state);
1694
+ boolean settling =
1695
+ viewDragHelper != null
1696
+ && (isReleasingView
1697
+ ? viewDragHelper.settleCapturedViewAt(child.getLeft(), top)
1698
+ : viewDragHelper.smoothSlideViewTo(child, child.getLeft(), top));
1699
+ if (settling) {
1700
+ setStateInternal(STATE_SETTLING);
1701
+ // STATE_SETTLING won't animate the material shape, so do that here with the target state.
1702
+ updateDrawableForTargetState(state, /* animate= */ true);
1703
+ stateSettlingTracker.continueSettlingToState(state);
1704
+ } else {
1705
+ setStateInternal(state);
1706
+ }
1707
+ }
1708
+
1709
+ private int getTopOffsetForState(@StableState int state) {
1710
+ switch (state) {
1711
+ case STATE_COLLAPSED:
1712
+ return collapsedOffset;
1713
+ case STATE_EXPANDED:
1714
+ return getExpandedOffset();
1715
+ case STATE_HALF_EXPANDED:
1716
+ return halfExpandedOffset;
1717
+ case STATE_HIDDEN:
1718
+ return parentHeight;
1719
+ default:
1720
+ // Fall through
1721
+ }
1722
+ throw new IllegalArgumentException("Invalid state to get top offset: " + state);
1723
+ }
1724
+
1725
+ private final ViewDragHelper.Callback dragCallback =
1726
+ new ViewDragHelper.Callback() {
1727
+
1728
+ private long viewCapturedMillis;
1729
+
1730
+ @Override
1731
+ public boolean tryCaptureView(@NonNull View child, int pointerId) {
1732
+ if (state == STATE_DRAGGING) {
1733
+ return false;
1734
+ }
1735
+ if (touchingScrollingChild) {
1736
+ return false;
1737
+ }
1738
+ if (state == STATE_EXPANDED && activePointerId == pointerId) {
1739
+ View scroll = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null;
1740
+ if (scroll != null && scroll.canScrollVertically(-1)) {
1741
+ // Let the content scroll up
1742
+ return false;
1743
+ }
1744
+ }
1745
+ viewCapturedMillis = System.currentTimeMillis();
1746
+ return viewRef != null && viewRef.get() == child;
1747
+ }
1748
+
1749
+ @Override
1750
+ public void onViewPositionChanged(
1751
+ @NonNull View changedView, int left, int top, int dx, int dy) {
1752
+ dispatchOnSlide(top);
1753
+ }
1754
+
1755
+ @Override
1756
+ public void onViewDragStateChanged(@State int state) {
1757
+ if (state == ViewDragHelper.STATE_DRAGGING && draggable) {
1758
+ setStateInternal(STATE_DRAGGING);
1759
+ }
1760
+ }
1761
+
1762
+ private boolean releasedLow(@NonNull View child) {
1763
+ // Needs to be at least half way to the bottom.
1764
+ return child.getTop() > (parentHeight + getExpandedOffset()) / 2;
1765
+ }
1766
+
1767
+ @Override
1768
+ public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) {
1769
+ @State int targetState;
1770
+ if (yvel < 0) { // Moving up
1771
+ if (fitToContents) {
1772
+ targetState = STATE_EXPANDED;
1773
+ } else {
1774
+ int currentTop = releasedChild.getTop();
1775
+ long dragDurationMillis = System.currentTimeMillis() - viewCapturedMillis;
1776
+
1777
+ if (shouldSkipHalfExpandedStateWhenDragging()) {
1778
+ float yPositionPercentage = currentTop * 100f / parentHeight;
1779
+
1780
+ if (shouldExpandOnUpwardDrag(dragDurationMillis, yPositionPercentage)) {
1781
+ targetState = STATE_EXPANDED;
1782
+ } else {
1783
+ targetState = STATE_COLLAPSED;
1784
+ }
1785
+ } else {
1786
+ if (currentTop > halfExpandedOffset) {
1787
+ targetState = STATE_HALF_EXPANDED;
1788
+ } else {
1789
+ targetState = STATE_EXPANDED;
1790
+ }
1791
+ }
1792
+ }
1793
+ } else if (hideable && shouldHide(releasedChild, yvel)) {
1794
+ // Hide if the view was either released low or it was a significant vertical swipe
1795
+ // otherwise settle to closest expanded state.
1796
+ if ((Math.abs(xvel) < Math.abs(yvel) && yvel > significantVelocityThreshold)
1797
+ || releasedLow(releasedChild)) {
1798
+ targetState = STATE_HIDDEN;
1799
+ } else if (fitToContents) {
1800
+ targetState = STATE_EXPANDED;
1801
+ } else if (Math.abs(releasedChild.getTop() - getExpandedOffset())
1802
+ < Math.abs(releasedChild.getTop() - halfExpandedOffset)) {
1803
+ targetState = STATE_EXPANDED;
1804
+ } else {
1805
+ targetState = STATE_HALF_EXPANDED;
1806
+ }
1807
+ } else if (yvel == 0.f || Math.abs(xvel) > Math.abs(yvel)) {
1808
+ // If the Y velocity is 0 or the swipe was mostly horizontal indicated by the X velocity
1809
+ // being greater than the Y velocity, settle to the nearest correct height.
1810
+ int currentTop = releasedChild.getTop();
1811
+ if (fitToContents) {
1812
+ if (Math.abs(currentTop - fitToContentsOffset)
1813
+ < Math.abs(currentTop - collapsedOffset)) {
1814
+ targetState = STATE_EXPANDED;
1815
+ } else {
1816
+ targetState = STATE_COLLAPSED;
1817
+ }
1818
+ } else {
1819
+ if (currentTop < halfExpandedOffset) {
1820
+ if (currentTop < Math.abs(currentTop - collapsedOffset)) {
1821
+ targetState = STATE_EXPANDED;
1822
+ } else {
1823
+ if (shouldSkipHalfExpandedStateWhenDragging()) {
1824
+ targetState = STATE_COLLAPSED;
1825
+ } else {
1826
+ targetState = STATE_HALF_EXPANDED;
1827
+ }
1828
+ }
1829
+ } else {
1830
+ if (Math.abs(currentTop - halfExpandedOffset)
1831
+ < Math.abs(currentTop - collapsedOffset)) {
1832
+ if (shouldSkipHalfExpandedStateWhenDragging()) {
1833
+ targetState = STATE_COLLAPSED;
1834
+ } else {
1835
+ targetState = STATE_HALF_EXPANDED;
1836
+ }
1837
+ } else {
1838
+ targetState = STATE_COLLAPSED;
1839
+ }
1840
+ }
1841
+ }
1842
+ } else { // Moving Down
1843
+ if (fitToContents) {
1844
+ targetState = STATE_COLLAPSED;
1845
+ } else {
1846
+ // Settle to the nearest correct height.
1847
+ int currentTop = releasedChild.getTop();
1848
+ if (Math.abs(currentTop - halfExpandedOffset)
1849
+ < Math.abs(currentTop - collapsedOffset)) {
1850
+ if (shouldSkipHalfExpandedStateWhenDragging()) {
1851
+ targetState = STATE_COLLAPSED;
1852
+ } else {
1853
+ targetState = STATE_HALF_EXPANDED;
1854
+ }
1855
+ } else {
1856
+ targetState = STATE_COLLAPSED;
1857
+ }
1858
+ }
1859
+ }
1860
+ startSettling(releasedChild, targetState, shouldSkipSmoothAnimation());
1861
+ }
1862
+
1863
+ @Override
1864
+ public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
1865
+ return MathUtils.clamp(
1866
+ top,
1867
+ getExpandedOffset(),
1868
+ getViewVerticalDragRange(child));
1869
+ }
1870
+
1871
+ @Override
1872
+ public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
1873
+ return child.getLeft();
1874
+ }
1875
+
1876
+ @Override
1877
+ public int getViewVerticalDragRange(@NonNull View child) {
1878
+ if (canBeHiddenByDragging()) {
1879
+ return parentHeight;
1880
+ } else {
1881
+ return collapsedOffset;
1882
+ }
1883
+ }
1884
+ };
1885
+
1886
+ void dispatchOnSlide(int top) {
1887
+ View bottomSheet = viewRef.get();
1888
+ if (bottomSheet != null && !callbacks.isEmpty()) {
1889
+ float slideOffset = calculateSlideOffsetWithTop(top);
1890
+ for (int i = 0; i < callbacks.size(); i++) {
1891
+ callbacks.get(i).onSlide(bottomSheet, slideOffset);
1892
+ }
1893
+ }
1894
+ }
1895
+
1896
+ @VisibleForTesting
1897
+ int getPeekHeightMin() {
1898
+ return peekHeightMin;
1899
+ }
1900
+
1901
+ /**
1902
+ * Disables the shaped corner {@link ShapeAppearanceModel} interpolation transition animations.
1903
+ * Will have no effect unless the sheet utilizes a {@link MaterialShapeDrawable} with set shape
1904
+ * theming properties. Only For use in UI testing.
1905
+ *
1906
+ * @hide
1907
+ */
1908
+ @RestrictTo(LIBRARY_GROUP)
1909
+ @VisibleForTesting
1910
+ public void disableShapeAnimations() {
1911
+ // Sets the shape value animator to null, prevents animations from occurring during testing.
1912
+ interpolatorAnimator = null;
1913
+ }
1914
+
1915
+ /**
1916
+ * Checks weather a nested scroll should be enabled. If {@code false} all nested scrolls will be
1917
+ * consumed by the bottomSheet.
1918
+ *
1919
+ * @hide
1920
+ */
1921
+ @RestrictTo(LIBRARY_GROUP)
1922
+ public boolean isNestedScrollingCheckEnabled() {
1923
+ return true;
1924
+ }
1925
+
1926
+ /**
1927
+ * Checks weather half expended state should be skipped when drag is ended. If {@code true}, the
1928
+ * bottomSheet will go to the next closest state.
1929
+ *
1930
+ * @hide
1931
+ */
1932
+ @RestrictTo(LIBRARY_GROUP)
1933
+ public boolean shouldSkipHalfExpandedStateWhenDragging() {
1934
+ return false;
1935
+ }
1936
+
1937
+ /**
1938
+ * Checks whether an animation should be smooth after the bottomSheet is released after dragging.
1939
+ *
1940
+ * @hide
1941
+ */
1942
+ @RestrictTo(LIBRARY_GROUP)
1943
+ public boolean shouldSkipSmoothAnimation() {
1944
+ return true;
1945
+ }
1946
+
1947
+ /**
1948
+ * Checks whether hiding gestures should be enabled while {@code isHideable} is set to true.
1949
+ *
1950
+ * @hide
1951
+ */
1952
+ @RestrictTo(LIBRARY_GROUP)
1953
+ public boolean isHideableWhenDragging() {
1954
+ return true;
1955
+ }
1956
+
1957
+ private boolean canBeHiddenByDragging() {
1958
+ return isHideable() && isHideableWhenDragging();
1959
+ }
1960
+
1961
+ /**
1962
+ * Checks whether the bottom sheet should be expanded after it has been released after dragging.
1963
+ *
1964
+ * @param dragDurationMillis how long the bottom sheet was dragged.
1965
+ * @param yPositionPercentage position of the bottom sheet when released after dragging. Lower
1966
+ * values mean that view was released closer to the top of the screen.
1967
+ * @hide
1968
+ */
1969
+ @RestrictTo(LIBRARY_GROUP)
1970
+ public boolean shouldExpandOnUpwardDrag(
1971
+ long dragDurationMillis, @FloatRange(from = 0.0f, to = 100.0f) float yPositionPercentage) {
1972
+ return false;
1973
+ }
1974
+
1975
+ /**
1976
+ * Sets whether this bottom sheet can hide when it is swiped down.
1977
+ *
1978
+ * @param hideable {@code true} to make this bottom sheet hideable.
1979
+ * @hide
1980
+ */
1981
+ @RestrictTo(LIBRARY_GROUP)
1982
+ public void setHideableInternal(boolean hideable) {
1983
+ this.hideable = hideable;
1984
+ }
1985
+
1986
+ /**
1987
+ * Gets the last stable state of the bottom sheet.
1988
+ *
1989
+ * @return One of {@link #STATE_EXPANDED}, {@link #STATE_HALF_EXPANDED}, {@link #STATE_COLLAPSED},
1990
+ * {@link #STATE_HIDDEN}.
1991
+ * @hide
1992
+ */
1993
+ @State
1994
+ @RestrictTo(LIBRARY_GROUP)
1995
+ public int getLastStableState() {
1996
+ return lastStableState;
1997
+ }
1998
+
1999
+ private class StateSettlingTracker {
2000
+ @State private int targetState;
2001
+ private boolean isContinueSettlingRunnablePosted;
2002
+
2003
+ private final Runnable continueSettlingRunnable =
2004
+ new Runnable() {
2005
+ @Override
2006
+ public void run() {
2007
+ isContinueSettlingRunnablePosted = false;
2008
+ if (viewDragHelper != null && viewDragHelper.continueSettling(true)) {
2009
+ continueSettlingToState(targetState);
2010
+ } else if (state == STATE_SETTLING) {
2011
+ setStateInternal(targetState);
2012
+ }
2013
+ // In other cases, settling has been interrupted by certain UX interactions. Do nothing.
2014
+ }
2015
+ };
2016
+
2017
+ void continueSettlingToState(@State int targetState) {
2018
+ if (viewRef == null || viewRef.get() == null) {
2019
+ return;
2020
+ }
2021
+ this.targetState = targetState;
2022
+ if (!isContinueSettlingRunnablePosted) {
2023
+ ViewCompat.postOnAnimation(viewRef.get(), continueSettlingRunnable);
2024
+ isContinueSettlingRunnablePosted = true;
2025
+ }
2026
+ }
2027
+ }
2028
+
2029
+ /** State persisted across instances */
2030
+ protected static class SavedState extends AbsSavedState {
2031
+ @State final int state;
2032
+ int peekHeight;
2033
+ boolean fitToContents;
2034
+ boolean hideable;
2035
+ boolean skipCollapsed;
2036
+
2037
+ public SavedState(@NonNull Parcel source) {
2038
+ this(source, null);
2039
+ }
2040
+
2041
+ public SavedState(@NonNull Parcel source, ClassLoader loader) {
2042
+ super(source, loader);
2043
+ //noinspection ResourceType
2044
+ state = source.readInt();
2045
+ peekHeight = source.readInt();
2046
+ fitToContents = source.readInt() == 1;
2047
+ hideable = source.readInt() == 1;
2048
+ skipCollapsed = source.readInt() == 1;
2049
+ }
2050
+
2051
+ public SavedState(Parcelable superState, @NonNull BottomSheetBehavior<?> behavior) {
2052
+ super(superState);
2053
+ this.state = behavior.state;
2054
+ this.peekHeight = behavior.peekHeight;
2055
+ this.fitToContents = behavior.fitToContents;
2056
+ this.hideable = behavior.hideable;
2057
+ this.skipCollapsed = behavior.skipCollapsed;
2058
+ }
2059
+
2060
+ /**
2061
+ * This constructor does not respect flags: {@link BottomSheetBehavior#SAVE_PEEK_HEIGHT}, {@link
2062
+ * BottomSheetBehavior#SAVE_FIT_TO_CONTENTS}, {@link BottomSheetBehavior#SAVE_HIDEABLE}, {@link
2063
+ * BottomSheetBehavior#SAVE_SKIP_COLLAPSED}. It is as if {@link BottomSheetBehavior#SAVE_NONE}
2064
+ * were set.
2065
+ *
2066
+ * @deprecated Use {@link #SavedState(Parcelable, BottomSheetBehavior)} instead.
2067
+ */
2068
+ @Deprecated
2069
+ public SavedState(Parcelable superstate, @State int state) {
2070
+ super(superstate);
2071
+ this.state = state;
2072
+ }
2073
+
2074
+ @Override
2075
+ public void writeToParcel(@NonNull Parcel out, int flags) {
2076
+ super.writeToParcel(out, flags);
2077
+ out.writeInt(state);
2078
+ out.writeInt(peekHeight);
2079
+ out.writeInt(fitToContents ? 1 : 0);
2080
+ out.writeInt(hideable ? 1 : 0);
2081
+ out.writeInt(skipCollapsed ? 1 : 0);
2082
+ }
2083
+
2084
+ public static final Creator<SavedState> CREATOR =
2085
+ new ClassLoaderCreator<SavedState>() {
2086
+ @NonNull
2087
+ @Override
2088
+ public SavedState createFromParcel(@NonNull Parcel in, ClassLoader loader) {
2089
+ return new SavedState(in, loader);
2090
+ }
2091
+
2092
+ @Nullable
2093
+ @Override
2094
+ public SavedState createFromParcel(@NonNull Parcel in) {
2095
+ return new SavedState(in, null);
2096
+ }
2097
+
2098
+ @NonNull
2099
+ @Override
2100
+ public SavedState[] newArray(int size) {
2101
+ return new SavedState[size];
2102
+ }
2103
+ };
2104
+ }
2105
+
2106
+ /**
2107
+ * A utility function to get the {@link BottomSheetBehavior} associated with the {@code view}.
2108
+ *
2109
+ * @param view The {@link View} with {@link BottomSheetBehavior}.
2110
+ * @return The {@link BottomSheetBehavior} associated with the {@code view}.
2111
+ */
2112
+ @NonNull
2113
+ @SuppressWarnings("unchecked")
2114
+ public static <V extends View> BottomSheetBehavior<V> from(@NonNull V view) {
2115
+ ViewGroup.LayoutParams params = view.getLayoutParams();
2116
+ if (!(params instanceof CoordinatorLayout.LayoutParams)) {
2117
+ throw new IllegalArgumentException("The view is not a child of CoordinatorLayout");
2118
+ }
2119
+ CoordinatorLayout.Behavior<?> behavior =
2120
+ ((CoordinatorLayout.LayoutParams) params).getBehavior();
2121
+ if (!(behavior instanceof BottomSheetBehavior)) {
2122
+ throw new IllegalArgumentException("The view is not associated with BottomSheetBehavior");
2123
+ }
2124
+ return (BottomSheetBehavior<V>) behavior;
2125
+ }
2126
+
2127
+ /**
2128
+ * Sets whether the BottomSheet should update the accessibility status of its {@link
2129
+ * CoordinatorLayout} siblings when expanded.
2130
+ *
2131
+ * <p>Set this to true if the expanded state of the sheet blocks access to siblings (e.g., when
2132
+ * the sheet expands over the full screen).
2133
+ */
2134
+ public void setUpdateImportantForAccessibilityOnSiblings(
2135
+ boolean updateImportantForAccessibilityOnSiblings) {
2136
+ this.updateImportantForAccessibilityOnSiblings = updateImportantForAccessibilityOnSiblings;
2137
+ }
2138
+
2139
+ private void updateImportantForAccessibility(boolean expanded) {
2140
+ if (viewRef == null) {
2141
+ return;
2142
+ }
2143
+
2144
+ ViewParent viewParent = viewRef.get().getParent();
2145
+ if (!(viewParent instanceof CoordinatorLayout)) {
2146
+ return;
2147
+ }
2148
+
2149
+ CoordinatorLayout parent = (CoordinatorLayout) viewParent;
2150
+ final int childCount = parent.getChildCount();
2151
+ if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) && expanded) {
2152
+ if (importantForAccessibilityMap == null) {
2153
+ importantForAccessibilityMap = new HashMap<>(childCount);
2154
+ } else {
2155
+ // The important for accessibility values of the child views have been saved already.
2156
+ return;
2157
+ }
2158
+ }
2159
+
2160
+ for (int i = 0; i < childCount; i++) {
2161
+ final View child = parent.getChildAt(i);
2162
+ if (child == viewRef.get()) {
2163
+ continue;
2164
+ }
2165
+
2166
+ if (expanded) {
2167
+ // Saves the important for accessibility value of the child view.
2168
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
2169
+ importantForAccessibilityMap.put(child, child.getImportantForAccessibility());
2170
+ }
2171
+ if (updateImportantForAccessibilityOnSiblings) {
2172
+ ViewCompat.setImportantForAccessibility(
2173
+ child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
2174
+ }
2175
+ } else {
2176
+ if (updateImportantForAccessibilityOnSiblings
2177
+ && importantForAccessibilityMap != null
2178
+ && importantForAccessibilityMap.containsKey(child)) {
2179
+ // Restores the original important for accessibility value of the child view.
2180
+ ViewCompat.setImportantForAccessibility(child, importantForAccessibilityMap.get(child));
2181
+ }
2182
+ }
2183
+ }
2184
+
2185
+ if (!expanded) {
2186
+ importantForAccessibilityMap = null;
2187
+ } else if (updateImportantForAccessibilityOnSiblings) {
2188
+ // If the siblings of the bottom sheet have been set to not important for a11y, move the focus
2189
+ // to the bottom sheet when expanded.
2190
+ viewRef.get().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
2191
+ }
2192
+ }
2193
+
2194
+ void setAccessibilityDelegateView(@Nullable View accessibilityDelegateView) {
2195
+ if (accessibilityDelegateView == null && accessibilityDelegateViewRef != null) {
2196
+ clearAccessibilityAction(
2197
+ accessibilityDelegateViewRef.get(), VIEW_INDEX_ACCESSIBILITY_DELEGATE_VIEW);
2198
+ accessibilityDelegateViewRef = null;
2199
+ return;
2200
+ }
2201
+ accessibilityDelegateViewRef = new WeakReference<>(accessibilityDelegateView);
2202
+ updateAccessibilityActions(accessibilityDelegateView, VIEW_INDEX_ACCESSIBILITY_DELEGATE_VIEW);
2203
+ }
2204
+
2205
+ private void updateAccessibilityActions() {
2206
+ if (viewRef != null) {
2207
+ updateAccessibilityActions(viewRef.get(), VIEW_INDEX_BOTTOM_SHEET);
2208
+ }
2209
+ if (accessibilityDelegateViewRef != null) {
2210
+ updateAccessibilityActions(
2211
+ accessibilityDelegateViewRef.get(), VIEW_INDEX_ACCESSIBILITY_DELEGATE_VIEW);
2212
+ }
2213
+ }
2214
+
2215
+ private void updateAccessibilityActions(View view, int viewIndex) {
2216
+ if (view == null) {
2217
+ return;
2218
+ }
2219
+ clearAccessibilityAction(view, viewIndex);
2220
+
2221
+ if (!fitToContents && state != STATE_HALF_EXPANDED) {
2222
+ expandHalfwayActionIds.put(
2223
+ viewIndex,
2224
+ addAccessibilityActionForState(
2225
+ view, R.string.bottomsheet_action_expand_halfway, STATE_HALF_EXPANDED));
2226
+ }
2227
+
2228
+ if ((hideable && isHideableWhenDragging()) && state != STATE_HIDDEN) {
2229
+ replaceAccessibilityActionForState(
2230
+ view, AccessibilityActionCompat.ACTION_DISMISS, STATE_HIDDEN);
2231
+ }
2232
+
2233
+ switch (state) {
2234
+ case STATE_EXPANDED:
2235
+ {
2236
+ int nextState = fitToContents ? STATE_COLLAPSED : STATE_HALF_EXPANDED;
2237
+ replaceAccessibilityActionForState(
2238
+ view, AccessibilityActionCompat.ACTION_COLLAPSE, nextState);
2239
+ break;
2240
+ }
2241
+ case STATE_HALF_EXPANDED:
2242
+ {
2243
+ replaceAccessibilityActionForState(
2244
+ view, AccessibilityActionCompat.ACTION_COLLAPSE, STATE_COLLAPSED);
2245
+ replaceAccessibilityActionForState(
2246
+ view, AccessibilityActionCompat.ACTION_EXPAND, STATE_EXPANDED);
2247
+ break;
2248
+ }
2249
+ case STATE_COLLAPSED:
2250
+ {
2251
+ int nextState = fitToContents ? STATE_EXPANDED : STATE_HALF_EXPANDED;
2252
+ replaceAccessibilityActionForState(
2253
+ view, AccessibilityActionCompat.ACTION_EXPAND, nextState);
2254
+ break;
2255
+ }
2256
+ case STATE_HIDDEN:
2257
+ case STATE_DRAGGING:
2258
+ case STATE_SETTLING:
2259
+ // Accessibility actions are not applicable, do nothing
2260
+ }
2261
+ }
2262
+
2263
+ private void clearAccessibilityAction(View view, int viewIndex) {
2264
+ if (view == null) {
2265
+ return;
2266
+ }
2267
+ ViewCompat.removeAccessibilityAction(view, AccessibilityNodeInfoCompat.ACTION_COLLAPSE);
2268
+ ViewCompat.removeAccessibilityAction(view, AccessibilityNodeInfoCompat.ACTION_EXPAND);
2269
+ ViewCompat.removeAccessibilityAction(view, AccessibilityNodeInfoCompat.ACTION_DISMISS);
2270
+
2271
+ int expandHalfwayActionId = expandHalfwayActionIds.get(viewIndex, View.NO_ID);
2272
+ if (expandHalfwayActionId != View.NO_ID) {
2273
+ ViewCompat.removeAccessibilityAction(view, expandHalfwayActionId);
2274
+ expandHalfwayActionIds.delete(viewIndex);
2275
+ }
2276
+ }
2277
+
2278
+ private void replaceAccessibilityActionForState(
2279
+ View child, AccessibilityActionCompat action, @State int state) {
2280
+ ViewCompat.replaceAccessibilityAction(
2281
+ child, action, null, createAccessibilityViewCommandForState(state));
2282
+ }
2283
+
2284
+ private int addAccessibilityActionForState(
2285
+ View child, @StringRes int stringResId, @State int state) {
2286
+ return ViewCompat.addAccessibilityAction(
2287
+ child,
2288
+ child.getResources().getString(stringResId),
2289
+ createAccessibilityViewCommandForState(state));
2290
+ }
2291
+
2292
+ private AccessibilityViewCommand createAccessibilityViewCommandForState(@State final int state) {
2293
+ return new AccessibilityViewCommand() {
2294
+ @Override
2295
+ public boolean perform(@NonNull View view, @Nullable CommandArguments arguments) {
2296
+ setState(state);
2297
+ return true;
2298
+ }
2299
+ };
2300
+ }
2301
+
2302
+
2303
+ @Nullable
2304
+ private static String getNativeId(View view) {
2305
+ Object tag = view.getTag(com.facebook.react.R.id.view_tag_native_id);
2306
+ return tag instanceof String ? (String)tag : null;
2307
+ }
2308
+
2309
+ @Nullable
2310
+ public static View findView(View root, String nativeId) {
2311
+ String tag = getNativeId(root);
2312
+ if (tag != null && tag.contains(nativeId)) {
2313
+ return root;
2314
+ } else {
2315
+ if (root instanceof ViewGroup) {
2316
+ ViewGroup viewGroup = (ViewGroup)root;
2317
+
2318
+ for(int i = 0; i < viewGroup.getChildCount(); ++i) {
2319
+ View view = findView(viewGroup.getChildAt(i), nativeId);
2320
+ if (view != null) {
2321
+ return view;
2322
+ }
2323
+ }
2324
+ }
2325
+
2326
+ return null;
2327
+ }
2328
+ }
2329
+ }