一、需求UI图
画了下大致的效果图如下图所示,只是一个简单的提醒弹窗,包含一个TextView和两个可点击的Button按钮,用于取消或确认。
二、代码设计步骤
该弹窗的设计及使用分为五个步骤:
(1)一个drawable:
dialog_background.xml设计,作为(2)中使用的背景,包含:
shape
corners:radius
solid:color
等属性设置。
(2)一个layout.xml:
alert_dialog.xml设计,使用dialog_background.xml作为背景。
(3)AlertDialogFragment.java,设计弹窗
(4)定义一个工具类DialogUtils,其中定义对应的showAlertDialog方法。
(5)在主界面MainActivity中对应的点击事件中,调用showAlertDialog方法显示该弹窗。
三、源码
前四步的代码以后均可直接复用,第五步根据实际开发需求稍作修改即可。
(1)一个drawable:
dialog_background.xml,作为整体的背景:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="15dp" />
<solid android:color="@color/cardview_shadow_start_color" />
</shape>
颜色值,形状等都可以在这边定义。
如圆角15dp,颜色值,不透明度等。
(2)一个layout.xml:
alert_dialog.xml设计
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/dialog_background">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="确认要关闭超速报警吗?"
android:textColor="@color/white"
android:textSize="22sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /</