以下文中是参照多个文章最终形成,先感谢他们的分享。
自定义对话框是本质是一个AlertDialog,需要的资源有布局、样式,然后在Activity弹出这个窗体即可。
一,布局
与普通的窗体布局没什么区别,例如自定义布局res\layout\popup_test.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/dialog_bg"><!--给弹出层增加一个背景色,否则弹出内容与下层边界不清楚,你可以尝试去掉看看效果-->
<TextView
android:id="@+id/tvTitle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是一个弹出窗口,啦啦啦。。。。"
android:textColor="#ffffff"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="@id/tvTitle1"
app:layout_constraintTop_toBottomOf="@id/tvTitle1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="测试。。。"
android:textColor="#ffffff" />
</RadioGroup>
</androidx.constraintlayout.widget.ConstraintLayout>
二,样式
在res\values\目录下增加一个styles.xml文件,内容如下:
<resources>
<style name="popupDialogTest" parent="android:style/Theme.Dialog">
<!-- 背景透明,设置圆角对话框必须设置背景透明,否则四角会有背景色小块-->
<item name="android:windowBackground">@android:color/transparent</item>
<!-- 没有标题 -->
<item name="android:windowNoTitle">true</item>
<!-- 背景模糊 -->
<item name="android:backgroundDimEnabled">true</item>
</style>
</resources>
在res\drawable\下增加一个dialog_bg.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp" />
<solid android:color="#3a3a3a" />
</shape>
三,构造窗体并显示
private AlertDialog dialogPopupTest = null;
public void doShowPopup(View view) {
if (dialogPopupTest == null) {
View popupView = LayoutInflater.from(this).inflate(R.layout.popup_test, null, false);
//获得布局里的各元素用于控制
//例如Button btTest1 = popupView.findViewById(R.id.btTest1);
//...
dialogPopupTest = new AlertDialog.Builder(this, R.style.popupDialogTest).setView(popupView).create();
//以下内容可以不要,用于对话框本身的透明
Window window = dialogPopupTest.getWindow();
WindowManager.LayoutParams attributes = window.getAttributes();
attributes.alpha = 0.7f;
window.setAttributes(attributes);
}
dialogPopupTest.show();
}
效果图如下: