2011-10-26 148 views
6

大家好,我正在通过单击按钮在android中创建一个警报对话框。我使用XML的onClick属性和调用函数。我的代码是警报对话框不显示

public void selectPhoneType(View view) 
{ 
    String [] item = {"Home", "Work", "Mobile", "Work Fax", "Home Fax", "Pager", "Other", "Custom"}; 
    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext()); 
    builder.setTitle("Select Label"); 
    AlertDialog alert = builder.create(); 
    alert.show();} 

但是这个代码不显示警告,并给予错误,如

BadTokenException: Unable to add window -- token null is not for an application. 

请告诉我,什么是错的这个代码。

+2

尝试:新AlertDialog.Builder(本) – anfy2002us

+1

嘿感谢它的工作,但请你解释一下我是什么这一点,并getAplicationContext之间的区别? –

回答

17
new AlertDialog.Builder(getApplicationContext()); 

我认为这是问题所在。您是否尝试过:

new AlertDialog.Builder(YourActivityClassName.this); 
+1

是的,我没有尝试这个,但做了这个工作后。怎么样?请解释我。 –

+1

您正在添加整个应用程序的上下文,而不是您想要显示对话框的特定活动。 这篇博文的底部有一些解释。 http://tech.shantanugoel.com/2010/07/08/badtokenexception-android-dialog-getapplicationcontext.html – NotACleverMan

+1

非常感谢。 –