展开时如何使 BottomSheetDialog 全屏显示并在其底部附加按钮?

How to make BottomSheetDialog fullcreen when expanded and make button attached at bottom of it?

问题

我需要为我的应用程序使用 BottomSheetDialog (com.google.android.material.bottomsheet),但它没有像我预期的那样工作,Bottom Sheet 展开时出现切割

我的实现

inline fun <T : ViewBinding> Context.makeBottomSheetDialog(
        crossinline bindingInflater: (LayoutInflater) -> T,
        isCancelable: Boolean = true,
        isHideable: Boolean = true,
        isFitContent: Boolean = true,
        peekHeight: Int? = null,
        onDismissListener: DialogInterface.OnDismissListener? = null,
): Pair<T, BottomSheetDialog> {
    val layout = bindingInflater.invoke(LayoutInflater.from(this@makeBottomSheetDialog))
    val dialog = BottomSheetDialog(this).apply {
        setContentView(layout.root)
        setOnDismissListener(onDismissListener)
        setCancelable(isCancelable)
    }.apply {
        behavior.apply {
            setHideable(isHideable)
            isFitToContents = isFitContent
            if(peekHeight != null) setPeekHeight(peekHeight)
        }
    }
    return Pair(layout, dialog)
}

我已经研究过这个问题,每个人都建议创建自己的 class,但就我而言,我希望它具有灵活的视图并且易于使用内联调用。当我看到 BottomSheetDialog 的基本代码时,我认为这是因为当 BottomSheet 展开时容器 (FrameLayout) 高度没有调整。

问题

我该如何解决这个问题?这让我也无法在视图底部附加按钮。 谢谢!

有一种方法可以做到这一点:

在 XML 对话框布局中:


 <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:id="@+id/sliderLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:behavior_hideable="true"
            app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

        // Place your layout code here and your code should be in one tag that can be any Layout.

        </RelativeLayout>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

在调用对话框的视图中,创建 RelativeLayout 类型的 BottomSheetBehavior 变量。

private lateinit var bottomSheetBehaviour: BottomSheetBehavior<RelativeLayout>

然后,像这样调用你的对话框,


 val dialog = BottomSheetDialog(this)
 val dialogBinding = binding of your dialog layout
 dialog.setContentView(dialogBinding.root)
 bottomSheetBehaviour = BottomSheetBehavior.from(dialogBinding.sliderLayout)
 dialog.show()

 bottomSheetBehaviour.state = BottomSheetBehavior.STATE_EXPANDED
 bottomSheetBehaviour.peekHeight = dialogBinding.sliderLayout.height

这将使您的对话框布局在用户向上滑动布局时全屏显示。