2011-10-26 151 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

非常感謝。 –