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

这个错误是我在看Android SDK文档时,在一个Button的监听器里写了一个自定义的处理条,

代码如下:
  

//自定义处理条
		dialog6.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				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();
			}
		});
 

问题出在这句Context mContext =  getApplicationContext(); 

应该写成Activity.this.  Activity所在的Activity.

这是解释http://tech.shantanugoel.com/2010/07/08/badtokenexception-android-dialog-getapplicationcontext.html

原文地址:https://www.cnblogs.com/andgoo/p/2094969.html