Android 对话框 - 基础对话框补充(不同的上下文创建 AlertDialog、AlertDialog 的三个按钮)

一、不同的上下文创建 AlertDialog

1、演示
(1)使用 Activity 上下文
java 复制代码
AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("普通对话框");
builder.setMessage("确定退出吗?");
builder.setPositiveButton("确定", (dialog, which) -> {
    Toast.makeText(this, "点击了确定", Toast.LENGTH_SHORT).show();
});
builder.setNegativeButton("取消", (dialog, which) -> {
    Toast.makeText(this, "点击了取消", Toast.LENGTH_SHORT).show();
});

AlertDialog alertDialog = builder.create();

alertDialog.show();
(2)使用 Application 上下文
  1. 使用 getApplication 方法获取的 Application 上下文
java 复制代码
AlertDialog.Builder builder = new AlertDialog.Builder(getApplication());

builder.setTitle("普通对话框");
builder.setMessage("确定退出吗?");
builder.setPositiveButton("确定", (dialog, which) -> {
    Toast.makeText(this, "点击了确定", Toast.LENGTH_SHORT).show();
});
builder.setNegativeButton("取消", (dialog, which) -> {
    Toast.makeText(this, "点击了取消", Toast.LENGTH_SHORT).show();
});

AlertDialog alertDialog = builder.create();

alertDialog.show();
  • 输出结果

    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

  1. 使用 getApplicationContext 方法获取的 Application 上下文
java 复制代码
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

builder.setTitle("普通对话框");
builder.setMessage("确定退出吗?");
builder.setPositiveButton("确定", (dialog, which) -> {
    Toast.makeText(this, "点击了确定", Toast.LENGTH_SHORT).show();
});
builder.setNegativeButton("取消", (dialog, which) -> {
    Toast.makeText(this, "点击了取消", Toast.LENGTH_SHORT).show();
});

AlertDialog alertDialog = builder.create();

alertDialog.show();
  • 输出结果

    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

2、小结
  1. 应该总是使用 Activity 上下文来创建对话框

  2. 避免使用 Application 上下文来创建对话框,对话框需要依附于一个窗口,而 Application 上下文没有关联的窗口


二、AlertDialog 的三个按钮

1、基本介绍
按钮 说明
Positive Button 积极 / 确定按钮,通常表示确认或继续操作
Negative Button 消极 / 取消按钮,通常表示取消操作
Neutral Button 中性按钮,提供第三种选择
2、演示
java 复制代码
AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("普通对话框");
builder.setMessage("确定退出吗?");
builder.setPositiveButton("确定", (dialog, which) -> {
    Toast.makeText(this, "点击了确定", Toast.LENGTH_SHORT).show();
});
builder.setNegativeButton("取消", (dialog, which) -> {
    Toast.makeText(this, "点击了取消", Toast.LENGTH_SHORT).show();
});
builder.setNeutralButton("稍后", (dialog, which) -> {
    Toast.makeText(this, "点击了稍后", Toast.LENGTH_SHORT).show();
});

AlertDialog alertDialog = builder.create();

alertDialog.show();