如何在Jetpack Compose的ModalBottomSheetLayout中配置HalfExpanded状态
修改ModalBottomSheetLayout半展开高度为30%的实现方法
要将ModalBottomSheetLayout的HalfExpanded状态高度改为屏幕的30%,可以通过自定义BottomSheetBehavior来实现,具体步骤如下:
自定义BottomSheetBehavior,重写
calculateHalfExpandedRatio方法
默认情况下该方法返回0.5f(对应屏幕50%高度),只需将其改为0.3f即可:class CustomBottomSheetBehavior<V : View>(context: Context, attrs: AttributeSet?) : BottomSheetBehavior<V>(context, attrs) { override fun calculateHalfExpandedRatio(): Float { return 0.3f // 设置为屏幕高度的30% } }在布局文件中绑定自定义Behavior
给ModalBottomSheetLayout指定自定义Behavior,注意填写完整的类包路径:<com.google.android.material.bottomsheet.ModalBottomSheetLayout android:id="@+id/bottomSheetLayout" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="com.yourpackage.CustomBottomSheetBehavior"> <!-- 底部表单内容布局 --> <LinearLayout android:id="@+id/bottomSheetContent" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"> <!-- 这里添加你的表单元素 --> </LinearLayout> </com.google.android.material.bottomsheet.ModalBottomSheetLayout>确保依赖Material Components库
如果项目未引入该库,在Module级别的build.gradle(或build.gradle.kts)中添加依赖:implementation 'com.google.android.material:material:1.9.0' // 可替换为最新稳定版本
注意事项
如果底部表单的内容高度本身小于屏幕的30%,半展开状态会自适应内容高度,不会强制拉伸表单。
内容的提问来源于stack exchange,提问作者Roshan
相关产品推荐
相关产品推荐

