【问题标题】:Showing AlertDialog when button is clicked problem单击按钮时显示 AlertDialog 问题
【发布时间】:2011-03-14 22:26:08
【问题描述】:

我的 Activity 中有按钮,我想在单击按钮时显示 AlertDialog:

  @Override
public void onClick(View view) {
     case R.id.btnDetailedCall:
        final String[] phoneArray=ad.getPhone().split(" ");

        if(phoneArray.length>1){

            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setTitle("Title");
            builder.setSingleChoiceItems(phoneArray, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    selectedPhone=phoneArray[which];
                }
            });
            AlertDialog dialog=builder.create();
            dialog.show();
  }

当我将“this”传递给 AlertDialog 构造函数时,代码运行正常,但对话框没有出现在屏幕上。我认为“this”在这里不是正确的参考,所以我尝试了 getBaseContext() 并得到了WindowManager$BadTockenException: Unable to add window -- tocken null is not for an application

将不胜感激任何帮助,谢谢。

【问题讨论】:

  • this 为我工作。您是否检查过其他事情是否按预期工作?
  • 如果你删除 builder.setSingleChoiceItems(...) 它会显示吗?

标签: android


【解决方案1】:

传递“this”可能会引用错误的对象,尝试传递“ClassName.this”,其中 ClassName 是您正在使用的实际类的名称 - 这是我在请求用户文本时使用的示例代码块在可能有帮助的应用程序中输入:

AlertDialog.Builder alert = new AlertDialog.Builder(MyClassName.this);
alert.setTitle("My title");
alert.setMessage("Some info I want to tell the user about");
final EditText input = new EditText(MyClassName.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Do it", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        try{
            int value = Integer.parseInt(input.getText().toString());
            doIt(value);
        }catch (Exception e){
            finish();
        }
    }
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // Canceled.
        finish();
    }
});
alert.show();

【讨论】:

  • 刚刚意识到您的代码和我的代码之间的关键区别在于您使用的是“builder.create()”,而我正在有效地使用“builder.show()”——看看是否使用了builder。 show() 有什么不同。
  • 试过了,但屏幕上仍然没有出现对话框。
【解决方案2】:

试试这个:

AlertDialog.Builder builder=new AlertDialog.Builder(className.this);

其中 className 是您的 Activity 类的名称,即主外部类。

【讨论】:

    【解决方案3】:

    你可以试试

    AlertDialog.Builder builder = new AlertDialog.Builder( getApplicationContext() );
    

    【讨论】:

    • 这会引发上述异常。
    【解决方案4】:

    尝试 builder.show() 而不是最后两行。

    【讨论】:

      【解决方案5】:

      尝试在您的 AlertDialog.Builder 语句前面添加“new”关键字,并通过在后续行中执行“.setTitle...”等将其他关键字链接到初始语句。我有一些这样的工作。

      例如

      new AlertDialog.Builder(this)
          .setTitle("Test")
          .create()
          .show();
      

      【讨论】:

        猜你喜欢
        • 2013-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多