我在
BottomSheetDialogFragment
中显示按钮时遇到一些问题。我希望它粘在底部工作表的底部,无论工作表是展开还是折叠。
见下图:
(我用草图来创建这个)
有什么建议或技巧吗?
以防万一,如果您知道如何向
bottomsheetdialog
添加上边距,我也很想知道;)
谢谢@Gnocalo,发帖。我已经实现了,请在我的github
中找到它步骤:
parent
视图 BottomSheetDialogFragment
parent
视图我解决这个问题的方法如下:
示例代码如下:
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 的底部
可能需要一段时间,但我遇到了同样的问题,所以我决定写一篇文章: https://dorianpavetic.medium.com/android-sticky-view-at-the-bottom-of-bottom-sheet-dialog-fragment-ac91242bc1b7
我正在寻找粘性底部按钮的解决方案,尽管想回答您有关设置底部页边距的其他问题。
因此您无法在底部工作表中添加边距,它基本上是由底部工作表的状态处理的。
您可以通过以下方式明确设置底部工作表的状态:
val bottomSheet = dialog!!.findViewById<View>(design_bottom_sheet) as FrameLayout
val behavior: BottomSheetBehavior<*> = BottomSheetBehavior.from<View>(bottomSheet)
behavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
要实现上述功能,您可以在回收器视图上将 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>