使用Material主题时BottomSheet弹窗外部无模糊效果该如何解决
解决方案
1. 修正底部弹窗主题配置
你当前使用的CustomBottomSheetDialogTheme继承的是过时的Design库主题,且缺少背景遮罩、模糊相关配置,替换为以下配置即可:
<style name="CustomBottomSheetDialogTheme" parent="Theme.MaterialComponents.Light.BottomSheetDialog"> <item name="bottomSheetStyle">@style/CustomBottomSheetStyle</item> <!-- 开启背景暗化 --> <item name="android:backgroundDimEnabled">true</item> <!-- 背景暗化透明度,0~1区间,数值越大背景越暗 --> <item name="android:backgroundDimAmount">0.5</item> <!-- Android 12及以上开启原生背景模糊 --> <item name="android:windowBlurBehindEnabled">true</item> <!-- 模糊半径,数值越大模糊效果越强,最大支持25 --> <item name="android:windowBlurBehindRadius">15</item> </style> <style name="CustomBottomSheetStyle" parent="Widget.MaterialComponents.BottomSheet.Modal"> <item name="android:background">@android:color/transparent</item> <!-- 可选:设置底部弹窗顶部圆角 --> <item name="cornerRadius">16dp</item> </style>
同时需要在AndroidManifest.xml对应的Activity标签下添加硬件加速配置,保证模糊效果正常生效:
<activity android:name=".你的Activity名" android:hardwareAccelerated="true"/>
2. 移除布局中错误的主题绑定
你在bottom_sheet_layout的根ConstraintLayout中加了style="@style/CustomBottomSheetDialogTheme",该主题是作用于Dialog窗口的,不能直接给View设置,直接删除这行属性即可避免冲突。
3. 代码初始化时显式指定主题
创建BottomSheetDialog时必须传入自定义的主题,不要使用默认构造方法:
// Kotlin示例 val bottomSheetDialog = BottomSheetDialog(this, R.style.CustomBottomSheetDialogTheme) bottomSheetDialog.setContentView(R.layout.bottom_sheet_layout) bottomSheetDialog.show()
// Java示例 BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this, R.style.CustomBottomSheetDialogTheme); bottomSheetDialog.setContentView(R.layout.bottom_sheet_layout); bottomSheetDialog.show();
低版本兼容说明
Android 12以下系统不支持原生窗口模糊,你可以通过监听BottomSheetBehavior的onStateChanged状态回调,当弹窗展开时手动对Activity根布局做模糊处理,可通过RenderScript或者第三方模糊工具库实现。
内容的提问来源于stack exchange,提问作者safauludogan
相关产品推荐
相关产品推荐

