普通对话框,主要调用系统的指令进行操作
第一步: 实例化一个Builder
//AlertDialog的构造方法时protected AlertDialog.Builder builder = new AlertDialog.Builder(this);
第二步:设置对话框样式
//2.设置对话框样式 builder.setTitle("提示"); builder.setMessage("您确定退出程序吗?");
第三步:设置按钮的点击事件
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); //展示 builder.setNegativeButton("取消", null);
第四步: 进行显示操作
builder.show();
完整java代码
package com.example.dialog; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.os.Bundle; 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 showNormalDialog(){ AlertDialog dialog = new AlertDialog.Builder(this).create(); dialog.setTitle("提示"); dialog.setMessage("您确定要退出程序吗?"); dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dialog.show(); } public void myClick(View view) { switch (view.getId()) { case R.id.normal_dialog_btn: //1.实例化一个Buidler //AlertDialog的构造方法时protected AlertDialog.Builder builder = new AlertDialog.Builder(this); //2.设置对话框样式 builder.setTitle("提示"); builder.setMessage("您确定退出程序吗?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); //展示 builder.setNegativeButton("取消", null); builder.show(); // AlertDialog dialog = builder.create(); // dialog.show(); break; } } }
activity.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/normal_dialog_btn" android:text="显示一个普通对话框" android:onClick="myClick"/> <Button android:id="@+id/diy_dialog_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="显示一个自定义对话框" android:onClick="myClick" /> </LinearLayout>