看不到如何禁用 AlertDialog Box

Can't see how to disable an AlertDialog Box

我正在尝试弄清楚如何在按下 negative/positive 按钮时绝对禁用 AlertDialog Box。我当前的应用程序可以在点击屏幕时运行,我希望我的应用程序在第一次点击时显示一个 AlertDialog Box。此框显示 "attention, some of the names are invented!",按钮为 "Ok!"(肯定按钮)和 "Don't remind this to me"(否定按钮)。在这两种情况下,我都希望应用程序在每次点击时停止显示 Box,因为这显然令人沮丧,并且在每次点击时显示消息毫无意义(考虑用户将每 5 秒点击 1 或 2 次)。所以我想弄清楚如何在第一次点击后禁用它。

现在,这就是我写的

   public void tap(View view) {

    final AlertDialog.Builder tapAlert = new AlertDialog.Builder(this);
    tapAlert.setMessage("The names are mostly invented!");
    tapAlert.setPositiveButton("Ok!", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();

        }
    });
    tapAlert.setNegativeButton("Don't remind it to me", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {


            dialog.cancel();

        }

    });
    tapAlert.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            // do nothing, just allow dialog to close
            // this happens on back button getting hit
        }
    });
    tapAlert.setTitle("Attention!");
    tapAlert.create();
    tapAlert.show();

只需在 class 级别创建一个布尔变量

boolean firstTap = true;

显示一次后再改

public void tap(View view) {

    final AlertDialog.Builder tapAlert = new AlertDialog.Builder(this);
    ...
    if (firstTap) {
        tapAlert.show();
        firstTap = false;
    }

如果您希望它在每次应用程序运行时第一次显示,这将起作用。如果您 曾经 希望它在第一次点击时显示,请将布尔值保存在 SharedPreferences 中并检查 Activity 何时开始。

甚至更好 是在调用 tap() 方法之前检查该变量。当 firstTapfalse 时不要调用它。