【问题标题】:android alert dialog not showingandroid警报对话框未显示
【发布时间】:2011-01-18 15:38:07
【问题描述】:

我试图在 onTouchListener 中显示警报,但无法显示。我对此很陌生,但我一直在关注一些好的教程,但无济于事。 这是代码的一部分...任何想法为什么此警报不会显示?

mSwitcher.setOnTouchListener(new OnTouchListener()
{
   public void onItemClick(AdapterView<?> parent, View v, int position, long id)
   {
   }

   @Override public boolean onTouch(View v, MotionEvent event)
   {
      // the attempt at the alert
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage("Are you sure you want to exit?")
             .setCancelable(false)
             .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      MyActivity.this.finish();
                   }
                })
             .setNegativeButton("No", new DialogInterface.OnClickListener()
                {
                   public void onClick(DialogInterface dialog, int id)
                   {
                      dialog.cancel();
                   }
                });
      AlertDialog alert = builder.create();
      return false;
   }
});

我认为我的结构还可以,但我什至无法编译。

【问题讨论】:

    标签: android dialog alert android-alertdialog


    【解决方案1】:

    尝试改变

    AlertDialog alert = builder.create();
    

    AlertDialog alert = builder.show();
    

    【讨论】:

    • 但是没有理由声明警报变量,因为它没有在块中使用。
    • 只需使用“builder.show();”你没有烦恼!
    【解决方案2】:

    我更新了代码,使括号位于正确的位置。它现在应该编译。正如 JLund 指出的那样,将最后一行从 builder.create(); 更改为 builder.show(); 应该可以。如果您希望保留builder.create(); 调用,只需在其后添加alert.show();

    【讨论】:

      【解决方案3】:

      您几乎完成了显示对话框警报,但您似乎忘记显示 AlertDialog,请使用 show()AlertDialog

      将此行添加到结尾您的代码,但在 return false; 之前 onTouch()

      alert.show();

      【讨论】: