自定义AlertDialog设置圆角背景时背景有白边??

起因

今天在写自定义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 contextint themeResId的构造方法的访问修饰符改成public

public 类名(@NonNull Context context, int themeResId) {
	super(context, themeResId);
	init(context);
}

在创建自定义AlertDialog对象的时候直接调用只有Context contextint themeResId的构造方法即可

创建自定义样式的通知框(AlertDialog)在Android中通常涉及到自定义布局、创建一个新的DialogFragment或者直接在Activity中使用AlertDialog.Builder。以下是基本步骤: 1. **创建XML布局**: 创建一个用于展示自定义样式的dialog主题。例如,你可以定义一个包含标题、消息、按钮等元素的布局文件。 ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp" android:background="?attr/colorPrimaryDark" android:theme="@style/Theme.MyAlertDialog"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:textColor="@color/white" android:paddingTop="16dp" /> <TextView android:id="@+id/message" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="@color/white" /> <Button android:id="@+id/button_positive" style="@style/Base.Widget.AppCompat.Button.Colored" android:text="确定" /> <!-- 可能还有其他按钮或控件 --> </LinearLayout> ``` 2. **创建自定义DialogFragment**: 如果你想将这个作为单独的组件复用,可以创建一个继承自DialogFragment的新类,并设置你的自定义布局作为内容视图。 ```java public class CustomAlertDialog extends DialogFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.my_custom_alert_dialog, container, false); } // ...添加事件监听器和其他定制功能 } ``` 3. **构建AlertDialog**: 使用`AlertDialog.Builder`创建对话框实例,然后设置自定义布局。 ```java AlertDialog.Builder builder = new AlertDialog.Builder(requireContext()); builder.setView(R.layout.my_custom_alert_dialog); // 使用XML布局ID builder.setTitle("自定义标题"); // 添加其他构建选项,如按钮 final CustomAlertDialog dialog = CustomAlertDialog.newInstance(); dialog.show(getFragmentManager(), "dialog"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值