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

来源:互联网 发布:用友nc6.5数据库 编辑:程序博客网 时间:2024/05/22 05:13

原文出处:http://blog.csdn.net/wsz1z154/article/details/7724912


在创建一个Dialog时,发生的错误:

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

[java] view plaincopy
  1. AlertDialog.Builder builder;  
  2. AlertDialog alertDialog;  
  3. Context mContext = getApplicationContext();        
  4. LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);  
  5. View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.layout_root));  
  6.   
  7. TextView text = (TextView) layout.findViewById(R.id.text);  
  8. text.setText("Hello, this is a custom dialog!");  
  9. ImageView image = (ImageView) layout.findViewById(R.id.image);  
  10. image.setImageResource(R.drawable.icon);  
  11. builder = new AlertDialog.Builder(mContext);  
  12. builder.setView(layout);  
  13. alertDialog = builder.create();  
  14. alertDialog.show();  
查询SDK帮助文档:


Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.


把这句Context mContext =  getApplicationContext(); 

改成Activity.this即可



详见新浪博文http://blog.sina.com.cn/s/blog_4b93170a0102e123.html

代码中出现如下错误:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

分析:

问题在于new AlertDialog.Builder(Context),虽然这里的参数是AlertDialog.Builder(Context context)

但我们不能使用getApplicationContext()获得的Context,而必须使用Activity的Context对象,因为只有一个Activity才能添加一个窗体。  

解决方法:

将new AlertDialog.Builder(Context context)中的参数用Activity的Context对象即可


该问题的具体原因可详见:http://blog.csdn.net/lmj623565791/article/details/40481055




0 0
原创粉丝点击