How to set expanded height (or min top offset) of BottomSheetDialogFragment?
Problem: You want to adjust the maximum expanded height of the BottomSheetDialogFragment. The default behavior is for the sheet to expand to the height of its content, but you want to be able to specify a custom height.
Solution: BottomSheetDialogFragment uses a BottomSheetBehavior to control its behavior. You can access this behavior by calling BottomSheetBehavior.from(View) on the BottomSheet view. Once you have the behavior, you can set the min top offset, which is the maximum expanded height of the sheet, using the setMinOffset() method.
- Create a Java class that extends
CoordinatorLayout.Behavior<V>
. - Copy and paste the code from the default
BottomSheetBehavior
file to your new one. - Modify the method
clampViewPositionVertical
with the following code:
- Add a new state:
- Modify the methods
onLayoutChild
,onStopNestedScroll
,BottomSheetBehavior<V> from(V view)
andsetState
(optional).
Here is an example of how to use the custom behavior:
```html BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet); behavior.setMinOffset(100); ```This will set the minimum expanded height of the sheet to 100 pixels.
Another Solution:
You can also set the expanded height of the sheet by modifying the layout params of the BottomSheet view. To do this, you need to get the FrameLayout that contains the sheet using the following code:
```html View bottomSheet = dialog.findViewById(R.id.design_bottom_sheet); ```Once you have the FrameLayout, you can then set the height of the sheet using the following code:
```html bottomSheet.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT; ```This will cause the sheet to expand to the full height of the screen.
Note: Keep in mind that the expanded height of the sheet is also affected by the peekHeight property of the BottomSheetBehavior. If you set the peekHeight to a value that is greater than the min top offset, the sheet will expand to the peekHeight instead of the min top offset.