实现方式
AlertDialog.Builder builder = new AlertDialog.Builder(context);
:构建Dialog的各种参数Builder.setIcon(int iconId)
:添加ICONBuilder.setTitle(CharSequence title)
:添加标题Builder.setMessage(CharSequence message)
:添加消息Builder.setView(View view)
:设置自定义布局Builder.creat()
:创建DialogBuilder.show
:显示对话框setPositiveButton
:确定按钮setNegativeButton
:取消按钮setNeutralButton
: 中间按钮
项目结构
主要代码
MainActivity.java
package com.study.myalertdialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void leoClick(View view) {
View dialogView = getLayoutInflater().inflate(R.layout.dialog_view, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher)
.setTitle("我是对话框")
.setMessage("今天怎么样")
.setView(dialogView)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e("leo", "onClick: 点击了确定按钮");
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e("leo", "onClick: 点击了取消按钮");
}
})
.setNeutralButton("中间", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e("leo", "onClick: 点击了中间按钮");
}
})
.create()
.show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="leoClick"
android:text="显示对话框"/>
</LinearLayout>
dialog_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
android:orientation="vertical">
<ImageView
android:src="@mipmap/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="今天热死了"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>