Android中如何实现带左右边距且遮罩正常显示的BottomSheet对话框?
问题原因
默认BottomSheetDialog的底层承载容器默认是白色背景,你给弹窗布局设置的左右边距实际是相对于这个白色容器的,露出的就是容器的白色底色,而非底层的半透明遮罩。
解决方案(无需第三方库)
方法1:代码动态设置容器透明
修改你的showATBottomSheet方法,在show()调用前添加一行代码,将底弹窗的承载容器背景设为透明:
private fun showATBottomSheet() { binding.AssignNewTaskButton.setOnClickListener { val bottomSheetDialog = BottomSheetDialog(this) bottomSheetDialog.setContentView(R.layout.bottom_sheet_assign_task) // 新增:将底弹窗容器背景设为透明 bottomSheetDialog.window?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)?.setBackgroundColor(Color.TRANSPARENT) bottomSheetDialog.show() } }
然后修改你的bottom_sheet_assign_task布局的根节点,添加左右边距即可:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bottom_sheet" android:layout_marginHorizontal="16dp" android:layout_marginBottom="16dp"> <!-- 原有子控件可以去掉自身的左右margin,避免重复缩进 --> </androidx.constraintlayout.widget.ConstraintLayout>
方法2:自定义全局透明样式(适合多处使用底弹窗的场景)
- 在
res/values/styles.xml中添加自定义样式:
<style name="TransparentBottomSheetDialog" parent="Theme.MaterialComponents.Light.BottomSheetDialog"> <item name="bottomSheetStyle">@style/TransparentBottomSheet</item> </style> <style name="TransparentBottomSheet" parent="Widget.MaterialComponents.BottomSheet"> <item name="android:background">@android:color/transparent</item> </style>
- 初始化Dialog时直接使用该样式,无需额外代码设置背景:
val bottomSheetDialog = BottomSheetDialog(this, R.style.TransparentBottomSheetDialog)
可选第三方库
如果需要更丰富的样式、动画定制能力,可以使用Material Dialogs的底弹窗扩展组件,只需要引入依赖即可快速实现带边距、自定义圆角、进场退场动画的底弹窗效果,无需手动处理透明背景问题。
内容的提问来源于stack exchange,提问作者Nikk
相关产品推荐
相关产品推荐

