BottomSheet设置STATE_EXPANDED仅填充内容,如何实现全屏展开?
解决BottomSheet仅展开至内容高度的问题
默认情况下,BottomSheetBehavior.STATE_EXPANDED只会让BottomSheet展开到内容自身的高度,当内容高度小于屏幕高度时,就不会占满全屏。要实现无论内容多少都全屏展开,可按以下步骤操作:
1. 调整布局结构
将BottomSheet的内容嵌套在NestedScrollView中,确保根布局高度设为match_parent,同时添加BottomSheet行为属性:
<?xml version="1.0" encoding="utf-8"?> <androidx.core.widget.NestedScrollView 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" app:layout_behavior="@string/bottom_sheet_behavior"> <!-- 你的原有内容容器(比如LinearLayout/RecyclerView等) --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- 列表项或其他控件 --> </LinearLayout> </androidx.core.widget.NestedScrollView>
2. 修改Dialog初始化代码
通过代码强制设置BottomSheet的最小高度为屏幕高度,并跳过折叠状态直接展开:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog // 获取BottomSheet的根View val bottomSheet = dialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) bottomSheet?.run { val behavior = BottomSheetBehavior.from(this) // 获取屏幕总高度 val screenHeight = resources.displayMetrics.heightPixels // 强制设置BottomSheet最小高度为屏幕高度 minimumHeight = screenHeight // 跳过折叠状态,直接进入展开模式 behavior.skipCollapsed = true // 设置为展开状态 behavior.state = BottomSheetBehavior.STATE_EXPANDED } return dialog }
关键说明
NestedScrollView保证即使内容高度不足屏幕高度,也能支持滚动操作,同时让布局撑满屏幕。- 设置
minimumHeight为屏幕高度,强制BottomSheet展开时占满全屏,不再受内容高度限制。 skipCollapsed = true避免BottomSheet停留在折叠状态,直接进入全屏展开模式。
内容的提问来源于stack exchange,提问作者Abhishek Tyagi
相关产品推荐
相关产品推荐

