BottomSheetDialogFragment – Disable Cancel on Touch Outside and Drag – Android

Disable Cancel on Touch Outside & on Back press

In order to create a BottomSheetDialogFragment which should not dismiss on touch outside or by clicking the Back button, we should use setCancelable(boolean cancelable) method of the DialogFragment.

val bottomSheetFragment = FixedBottomSheetFragment.getInstance()
bottomSheetFragment.isCancelable = false // property syntax for setCancelable()
bottomSheetFragment.show(supportFragmentManager, bottomSheetFragment.tag)

Make BottomSheetDialogFragment always Expanded

If we want to make the BottomSheetDialogFragment to be expanded always. Then, we have to set the BottomSheetBehavior.STATE_EXPANDED to the dialog behaviour. It is better to set the state in onViewCreated() lifecycle method of the Fragment.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    
    if (dialog is BottomSheetDialog) {
        val behaviour = (dialog as BottomSheetDialog).behavior
        behaviour.state = BottomSheetBehavior.STATE_EXPANDED
    }
}

Disable drag of BottomSheetDialogFragment

Even if we have made the BottomSheetDialogFragment as expanded, user can hold the top part of the BottomSheet and drag to show peek view. It can also be disabled by overriding onStateChanged(). This will set the expanded state even if user drags the view.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    if (dialog is BottomSheetDialog) {
        val behaviour = (dialog as BottomSheetDialog).behavior
        behaviour.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                    behaviour.state = BottomSheetBehavior.STATE_EXPANDED
                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {
            }
        })
    }
}