转于:http://blog.youkuaiyun.com/wsz1z154/article/details/7724912
--------------------------------------------------------------------------------
在创建一个Dialog时,发生的错误:
Unable to add window -- token null is not for an application
- 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即可
解决Android应用中创建Dialog时的错误问题
本文探讨了在Android应用开发中遇到的创建Dialog时出现的错误:Unable to add window -- token null is not for an application。通过调整Context的引用方式,从getApplicationContext()更改为Activity.this,成功解决了问题。文章详细介绍了错误原因及解决步骤,为开发者提供了实用的解决方案。
2万+

被折叠的 条评论
为什么被折叠?



