Home > Software design >  How to set BottomSheetDialogFragment to fullScreen?
How to set BottomSheetDialogFragment to fullScreen?

Time:03-23

I'm trying to make my BottomSheetDialogFragment to be fullscreen when it's opened, the issue is that in any case the Dialog is shown half of screen height.

I've tried to set the peekHeight as the following:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    dialog?.setOnShowListener { dialog ->
        val bottomSheetBehavior: BottomSheetBehavior<*> = (dialog as BottomSheetDialog).behavior
        bottomSheetBehavior.peekHeight = Resources.getSystem().displayMetrics.heightPixels
        bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
    }
}

But the Dialog is shown as same as without the peekHeight.

Then i've tried to add android:theme="@android:style/Theme.Material.Light.NoActionBar.Fullscreen"

In my BottomSheet layout but still had the same result.

CodePudding user response:

Use this

 fun setupRatio(context: Context, bottomSheetDialog: BottomSheetDialog, percetage: Int) {
    //id = com.google.android.material.R.id.design_bottom_sheet for Material Components
    //id = android.support.design.R.id.design_bottom_sheet for support librares
    val bottomSheet =
        bottomSheetDialog.findViewById<View>(R.id.design_bottom_sheet) as FrameLayout
    val behavior: BottomSheetBehavior<*> = BottomSheetBehavior.from(bottomSheet)
    val layoutParams = bottomSheet.layoutParams
    layoutParams.height = getBottomSheetDialogDefaultHeight(context, percetage)
    bottomSheet.layoutParams = layoutParams
    behavior.state = BottomSheetBehavior.STATE_EXPANDED
}

call this into onStart in your dialog

override fun onStart() {
    super.onStart()
    setupRatio(requireContext(),dialog as BottomSheetDialog,100)
}

 private fun getBottomSheetDialogDefaultHeight(context: Context, percetage: Int): Int {
    return getWindowHeight(context) * percetage / 100
}

   private fun getWindowHeight(context: Context): Int {
    // Calculate window height for fullscreen use
    val displayMetrics = DisplayMetrics()
    (context as Activity?)!!.windowManager.defaultDisplay.getMetrics(displayMetrics)
    return displayMetrics.heightPixels
}
  • Related