AlertDialog顯示錯誤 Unable to add window token null is not for an application

在listView的onItemClick函數中顯示一個AlertDialog,出現如下錯誤

Xml代碼  收藏代碼
  1. 08-07 21:26:43.506: ERROR/AndroidRuntime(9390): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application  

後google解決。

原來代碼中顯示語句如下

Java代碼  收藏代碼
  1. AlertDialog imageDialog = new AlertDialog.Builder(context).setTitle("狀態操作").setItems(items, listener).create();  
  2.                 imageDialog.show();  

其中context爲在OnCreate中

Java代碼  收藏代碼
  1. context = getApplicationContext();  

 得到

 

異常原因:AlertDialog創建語句

Java代碼  收藏代碼
  1. public AlertDialog.Builder (Context context)   

 中,不能使用getApplicationContext()得到的context,而必須使用Activity,所以解決如下

 

解決方法:語句修改爲

Java代碼  收藏代碼
  1. AlertDialog imageDialog = new AlertDialog.Builder(Activity.this).setTitle("狀態操作").setItems(items, listener).create();  
  2.                 imageDialog.show();  

 其中的Activity爲當前Activity的名稱

 

參考:

http://blog.csdn.net/yimo29/article/details/6004782

發佈了68 篇原創文章 · 獲贊 14 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章