带有底部粘性按钮的BottomSheetDialogFragment

问题描述 投票:0回答:5

我在

BottomSheetDialogFragment
中显示按钮时遇到一些问题。我希望它粘在底部工作表的底部,无论工作表是展开还是折叠。

见下图:

What I want to do

(我用草图来创建这个)

有什么建议或技巧吗?

以防万一,如果您知道如何向

bottomsheetdialog
添加上边距,我也很想知道;)

android bottom-sheet
5个回答
7
投票

谢谢@Gnocalo,发帖。我已经实现了,请在我的github

中找到它

步骤:

  • 找到
    parent
    视图
    BottomSheetDialogFragment
  • 扩充您的自定义视图并将其附加到
    parent
    视图
  • 调整底页的边距以避免视图重叠


2
投票

我解决这个问题的方法如下:

  1. 实现BottomSheetDialogFragment
  2. 覆盖 onCreateDialog
  3. 获取bottomSheetDialog的参考并设置onShowListener
  4. 从我的布局中删除按钮并将其添加到 R.id.container (当然,您可以通过编程方式创建自己的按钮,我这样做是为了更轻松地格式化按钮视图)。这样您的按钮将位于 R.id.design.bottom.sheet 上方,因为 R.id.container 是它的父级!

示例代码如下:

    val bottomSheetDialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
    bottomSheetDialog.setOnShowListener {
        val dialog = it as BottomSheetDialog

            dialog.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout
        val containerLayout: FrameLayout =
            dialog.findViewById<FrameLayout>(com.google.android.material.R.id.container) as FrameLayout
        val button = binding.submitButton
        val parent = button.parent as ViewGroup
        parent.removeView(button)
        containerLayout.addView(button, containerLayout.childCount)
    }
    return bottomSheetDialog

这样,您的底部工作表将正常响应触摸,并且按钮将保留在父级工作表上的位置。

如有任何疑问,请随时询问。

编辑

不要忘记定义布局参数/将按钮定位在 R.id.container 的底部


1
投票

可能需要一段时间,但我遇到了同样的问题,所以我决定写一篇文章: https://dorianpavetic.medium.com/android-sticky-view-at-the-bottom-of-bottom-sheet-dialog-fragment-ac91242bc1b7


0
投票

我正在寻找粘性底部按钮的解决方案,尽管想回答您有关设置底部页边距的其他问题。

因此您无法在底部工作表中添加边距,它基本上是由底部工作表的状态处理的。

您可以通过以下方式明确设置底部工作表的状态:

val bottomSheet = dialog!!.findViewById<View>(design_bottom_sheet) as FrameLayout
val behavior: BottomSheetBehavior<*> = BottomSheetBehavior.from<View>(bottomSheet)
behavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED

0
投票

要实现上述功能,您可以在回收器视图上将 constrainedHeight 设置为 true。此外,将回收器从底部限制到按钮顶部,并将按钮限制到末端。参考下面的代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/recycler_view"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constrainedHeight="true"
        app:layout_constraintBottom_toTopOf="@id/button"/>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent">
    </Button>

</androidx.constraintlayout.widget.ConstraintLayout>
© www.soinside.com 2019 - 2024. All rights reserved.