How to show BottomSheetDialogFragment with left/right/bottom margin?

Viewed 3282

BottomSheetDialogFragment is shown with full screen width and there is no bottom margin. I want to set the left/right and bottom margin.

I know we can use BottomSheetBehaviour and apply it to a View object in our layout. But I want to use BottomSheetDialogFragment

2 Answers

You probably shouldn't have a bottom margin (why shouldn't it extend to the bottom of the screen?), but you can set horizontal margin by modifying the layout once it's set up by BottomSheetDialog. The sheet loads a layout resource called design_bottom_sheet_dialog.xml. If you open that file, you can see that the sheet is actually loaded into a FrameLayout with id=@+id/design_bottom_sheet. Since the design resources are added to your app, you can use the IDs from this library in your code.

The strategy is simply, find the FrameLayout, get its LayoutParams, and change the margins there. To do this, subclass BottomSheetDialogFragment to add the override below.

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    val sheet: View? = dialog?.findViewById(R.id.design_bottom_sheet)
    val sheetLP = sheet?.layoutParams as? ViewGroup.MarginLayoutParams?
    sheetLP?.marginStart = this.resources.getDimensionPixelSize(R.dimen.bottomSheetHMargin) <-- your margin value dp
    sheetLP?.marginEnd = sheetLP!!.marginStart
}

Note, if the library changes the layout file, the code will not crash but could stop working. I have tested this on 1.2.1 of the library.

Related