您的位置:首页 > 移动开发

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

2014-10-09 16:49 211 查看
原文出处:http://blog.csdn.net/wsz1z154/article/details/7724912

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

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

[java] view
plaincopy

AlertDialog.Builder builder;

AlertDialog alertDialog;

Context mContext = getApplicationContext();

LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);

View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);

text.setText("Hello, this is a custom dialog!");

ImageView image = (ImageView) layout.findViewById(R.id.image);

image.setImageResource(R.drawable.icon);

builder = new AlertDialog.Builder(mContext);

builder.setView(layout);

alertDialog = builder.create();

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对象即可

该问题的具体原因可详见:/article/1580277.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐