原文出处:http://blog.csdn.net/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();
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.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