Android DialogFragment添加阴影效果后无法移除弹窗背景如何解决
问题根因
你代码中对弹窗Window的背景做了重复赋值:先调用getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT))设置透明背景,下一行立刻调用setBackgroundDrawableResource(android.R.drawable.dialog_holo_light_frame)设置了系统自带的不透明弹窗背景资源,直接覆盖了之前的透明配置,导致背景无法透明。
另外你布局中已经使用了带elevation属性的MaterialCardView,本身自带原生阴影效果,完全不需要通过设置系统弹窗背景来实现阴影。
修复方案
- 移除Window背景重复赋值的代码行,调整配置顺序避免属性失效,修改后的
sort_image_dialog_fragment.java对应逻辑如下:
public class sort_image_dialoge_fragment extends DialogFragment { @Nullable @org.jetbrains.annotations.Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.sort_image, container, false); // 如果你用MaterialCardView做容器,根布局不需要额外设置背景,可删掉下面这行 // view.setBackgroundResource(R.drawable.dialog_rounded_background); if (getDialog() != null && getDialog().getWindow() != null) { // 先请求无标题特性,放在最前面避免配置不生效 getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); // 只保留一次透明背景设置 getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); getDialog().getWindow().setDimAmount(0.8f); getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); } return view; } @Override public int getTheme() { return R.style.NoBackgroundDialogTheme; } }
- 确认你使用的
R.style.NoBackgroundDialogTheme配置正确,参考配置如下:
<style name="NoBackgroundDialogTheme" parent="Theme.MaterialComponents.Dialog"> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowIsFloating">true</item> <item name="android:windowNoTitle">true</item> <item name="android:backgroundDimEnabled">true</item> </style>
调整后即可实现透明背景+MaterialCardView自带阴影的效果,不会出现多余的系统弹窗背景。
内容的提问来源于stack exchange,提问作者Vasant Raval
相关产品推荐
相关产品推荐

