我正在实现一个 BottomSheetDialogFragment,我想最初填充一半屏幕,并能够将其向上拖动到全屏或向下拖动以关闭。为了简化实现以找到问题的根源,我创建了一个简单的布局文件,它只有红色背景和文本视图。我遇到的问题是,即使我将behavior.state设置为STATE_HALF_EXPANDED,底部工作表对话框的顶部也位于屏幕的中间点,但背景会环绕以适合我的文本视图,而不是扩展以填充下面的所有内容它。我仍然可以将其拖动到全屏,但同样,背景会包裹到我的文本视图,而不是填充下面的可用空间。同样,如果我删除 textView,那么除了 BottomSheetDialogFragment 后面的黑色不透明背景之外,什么也不会显示。
这是我用于 BottomSheetDialogFragment (text.xml) 的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000">
<TextView
android:id="@+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
这是我对 BottomSheetDialogFragment 的实现:
class TestBottomSheet: BottomSheetDialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.test, container, false)
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
val behavior = BottomSheetBehavior.from(requireView().parent as View)
behavior.peekHeight = resources.displayMetrics.heightPixels / 2
behavior.isHideable = true
behavior.isDraggable = true
behavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
}
}
这是我的活动中的函数,显示了 BottomSheetDialogFragment。
private val onButtonClick = View.OnClickListener {
val bottomSheetFragment = TestBottomSheet()
bottomSheetFragment.show(supportFragmentManager, "BottomSheetDialog")
}
以下是我所看到的屏幕截图:
当“behavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED”时
我也尝试将 test.xml 包装在 CoordinatorLayout 中,并得到相同的结果。
我希望发生的是红色背景填充一半屏幕,文本视图居中,因为此 BottomSheetDialogFragment 的最终结果将具有可变内容,可能占用超过或小于屏幕大小的一半,但 BottomSheetDialogFragment 应该始终占据一半屏幕,如果需要,可以将其拖动到全屏。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.post {
val parent = view.parent as View
val params = parent.layoutParams
val behavior = (params as ViewGroup.LayoutParams).apply {
height = (resources.displayMetrics.heightPixels * 0.5).toInt()
}
parent.layoutParams = behavior
}
}