2011-03-12 85 views
1

我已经在我的活动得到了按钮,我想表明AlertDialog按钮被点击时:显示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(); 
    } 

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

会明白任何帮助,谢谢。

+0

'我this'工作。你有没有检查,如果别的没有按预期工作? – Maaalte 2011-03-12 12:44:11

+0

如果你删除builder.setSingleChoiceItems(...)它显示吗? – aspartame 2011-03-12 12:50:08

回答

0

传递“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(); 
+0

刚刚意识到你的代码和我之间的主要区别在于使用的是“builder.create()”,而我有效利用“builder.show()” - 看是否使用builder.show()有什么差别。 – Kaiesh 2011-03-12 12:31:21

+0

尝试过,但对话框仍然没有出现在屏幕上。 – 2011-03-12 12:51:32

0

试试这个:

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

其中的className是你的Activity类即主外类的名称。

+0

这没有奏效。 – 2011-03-12 12:25:52

0

您可以尝试

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

这会抛出上面提到的异常。 – 2011-03-12 12:35:14

0

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

0

尝试只是增加了“新”的关键字在你的AlertDialog.Builder声明前,通过只是在做“.setTitle ......”等后续线上的其他链接到最初的声明。我有一些这样的工作。

Ex。

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