起因
今天在写自定义AlertDialog的时候,这个AlertDialog的背景是白色圆角矩形,最后上机发现圆角没了,于是把绑定自定义AlertDialog的layout的背景改成黑色,发现圆角出来了,但是仔细看就会发现,这个黑色和AlertDialog自带的蒙版颜色是有区别的
原因
Android自带的style会使用白色背景,设置了background后会使用设置的background覆盖在上面,但是没有覆盖到原本白色背景的部分还是会存在
解决
在themes.xml中添加一个style
<style name="DialogNoBackground" parent="ThemeOverlay.Material3.MaterialAlertDialog">
<item name="android:windowBackground">#00000000</item>
</style>
然后在创建自定义AlertDialog对象时候调用父类的
protected AlertDialog(@NonNull Context context, int themeResId)
两种调用方法
①继承AlertDialog后,重写构造方法时把只有一个Context
的构造方法调用父类的构造方法改为
super(context,R.style.DialogNoBackground)
在创建自定义AlertDialog对象的时候直接调用只有一个Context
的构造方法即可
②继承AlertDialog后,重写构造方法时把有Context context
和int themeResId
的构造方法的访问修饰符改成public
public 类名(@NonNull Context context, int themeResId) {
super(context, themeResId);
init(context);
}
在创建自定义AlertDialog对象的时候直接调用只有Context context
和int themeResId
的构造方法即可