禁用 BottomSheetDialogFragment 拖动

69 阅读1分钟

在 Material Design 1.2.0 发布后,有一种更简单的方法可以实现相同的目的。

setdraggable

方案一 BottomSheetDialogFragment 重写onCreateDialog:

     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val bottomSheetDialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
        bottomSheetDialog.setOnShowListener {
            val bottomSheet = bottomSheetDialog
                .findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)

            if (bottomSheet != null) {
                val behavior: BottomSheetBehavior<*> = BottomSheetBehavior.from(bottomSheet)
                behavior.isDraggable = false
            }
        }
        return bottomSheetDialog
    }

方案二、在style中添加:

     <style name="DisableDraggingBottomSheetDialogStyle" parent="Theme.MaterialComponents.Light.BottomSheetDialog">
        <item name="behavior_draggable">false</item>
    </style>

然后在dialog的 onCreate 中设置style:

     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NORMAL, R.style.DisableDraggingBottomSheetDialogStyle)
    }

BottomSheetDialogFragment 当软键盘弹出时,会调整窗口的大小以便留出足够的空间给软键盘

整个window 从底部整体抬升键盘的高度,顶部不会被顶上去,中间区域被下面顶上的内容覆盖。

<item name="android:windowSoftInputMode">adjustResize</item>

BottomSheetDialogFragment沉浸式效果

<item name="android:windowIsFloating">false</item>