Android v21下移除圆角Bottom Sheet背后白色背景问题求助
解决Android v21 BottomSheet圆角背景下的白色残留问题
问题原因
你看到的白色背景并非来自自定义布局,而是BottomSheetDialog自带的默认白色容器,自定义布局的圆角只是覆盖在它上方,导致角落露出底层白色。
解决方案
1. 清理布局冗余配置
你的ConstraintLayout同时设置了android:background和android:backgroundTint,由于shape文件中已经定义了填充色,保留android:background="@drawable/bottom_sheet_layout"即可,删除android:backgroundTint="@color/foreground"。
修改后的布局代码:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context="create_notes.BottomSheet" android:clipToOutline="true" android:padding="@dimen/dp16" android:background="@drawable/bottom_sheet_layout"> //.... </androidx.constraintlayout.widget.ConstraintLayout>
2. 给BottomSheetDialog设置透明背景
在显示弹窗的代码中添加透明背景配置:
直接使用BottomSheetDialog的情况
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(context); bottomSheetDialog.setContentView(R.layout.your_bottom_sheet_layout); // 适配v21+版本设置透明背景 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { bottomSheetDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } else { bottomSheetDialog.getWindow().setBackgroundDrawable(null); } bottomSheetDialog.show();
使用BottomSheetDialogFragment的情况
在onCreateDialog方法中处理:
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState); dialog.setContentView(R.layout.your_bottom_sheet_layout); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } else { dialog.getWindow().setBackgroundDrawable(null); } return dialog; }
3. 可选:调整弹窗默认显示高度
如果需要弹窗默认只露出部分内容,可添加以下代码设置peek高度:
BottomSheetBehavior behavior = BottomSheetBehavior.from((View) bottomSheetDialog.getContentView().getParent()); behavior.setPeekHeight(300); // 替换为你需要的高度值
完成以上设置后,BottomSheet底层的白色背景会被透明替换,自定义的圆角背景就能完整显示,不会有角落的白色残留。
内容的提问来源于stack exchange,提问作者hab
相关产品推荐
相关产品推荐

