【问题标题】:Can't see how to disable an AlertDialog Box看不到如何禁用警报对话框
【发布时间】:2015-06-09 17:48:57
【问题描述】:

我试图弄清楚当我按下负/正按钮时如何明确禁用警报对话框。我当前的应用程序可以点击屏幕,我希望我的应用程序在第一次点击时显示一个警报对话框。这个盒子说“注意,有些名字是发明的!”按钮是“确定!”(正面按钮)和“不要提醒我”(负面按钮)。在这两种情况下,我都希望应用程序在每次点击时停止显示 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();

【问题讨论】:

  • java != javascript ftfy

标签: java android alert


【解决方案1】:

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

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 时不要调用它。

【讨论】:

  • 刚刚尝试过,它运行顺利,谢谢 ;) 只是一个问题:如果我想让 AlertDialog 在每次用户按下“确定!”时应用程序启动时可见怎么办?如果用户按下“不要提醒我!”,并且永远不会更明显?我应该使用 SharedPreferences 吗?
  • 是的,SharedPreferences。如果它是假的,只需保存一个布尔值,不要显示它
  • 对不起,如果我这么不专业,你能给我一个代码示例吗?我的意思是,我正在尝试查看如何通过 SharedPreferences 保存它,但在找到正确的指南时遇到了一些问题:)
  • 我的答案中的链接给出了一个很好的例子,并且在互联网上的 SO 和其他地方有很多可以让你开始使用它。和here is an example 的更深入的设置活动
猜你喜欢
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
相关资源
最近更新 更多