Android中为全屏宽度的BottomSheetDialog添加阴影
为BottomSheetDialog添加阴影的几种实现方式
方法1:利用View的elevation属性(推荐,Android 5.0+)
你的布局根是ConstraintLayout,直接给它添加android:elevation和android:outlineProvider属性即可,系统会自动生成匹配圆角的阴影:
修改布局代码:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bottom_sheet_rounded_corner" android:elevation="8dp" android:outlineProvider="background"> <!-- 你的子View内容 --> </androidx.constraintlayout.widget.ConstraintLayout>
android:elevation:控制阴影的强弱,数值越大阴影越明显android:outlineProvider="background":让系统根据背景Drawable的圆角形状生成阴影轮廓,避免阴影还是矩形的问题
方法2:使用LayerDrawable叠加阴影层(兼容低版本)
如果需要兼容Android 5.0以下,可以把阴影和圆角背景合并成一个LayerDrawable:
- 先创建阴影层的drawable(
shadow_layer.xml):
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#40000000"/> <!-- 半透明黑色作为阴影 --> <corners android:radius="8dp"/> <padding android:top="2dp" android:left="2dp" android:right="2dp" android:bottom="2dp"/> </shape>
- 创建LayerDrawable(
bottom_sheet_with_shadow.xml),将阴影层放在底层,圆角背景层放在上层:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 阴影层 --> <item> <bitmap android:src="@drawable/shadow_layer" android:gravity="fill"/> </item> <!-- 圆角背景层,设置margin让阴影显示出来 --> <item android:top="2dp" android:left="2dp" android:right="2dp" android:bottom="0dp"> <shape> <solid android:color="@color/solidnight"/> <corners android:topLeftRadius="8dp" android:topRightRadius="8dp"/> </shape> </item> </layer-list>
- 把布局的
android:background替换成这个LayerDrawable:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bottom_sheet_with_shadow"> <!-- 你的子View内容 --> </androidx.constraintlayout.widget.ConstraintLayout>
方法3:调整BottomSheetDialog的Window属性
如果上面的方法没生效,可能是BottomSheetDialog的默认Window设置覆盖了阴影,可以在代码里手动设置:
val bottomSheetDialog = BottomSheetDialog(this) bottomSheetDialog.setContentView(R.layout.your_bottom_sheet_layout) // 获取BottomSheet的根布局 val bottomSheet = bottomSheetDialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) bottomSheet?.let { it.elevation = 8f it.outlineProvider = ViewOutlineProvider.BACKGROUND } bottomSheetDialog.show()
内容的提问来源于stack exchange,提问作者Seb
相关产品推荐
相关产品推荐

