Dialog显示引发异常
现象:BadTokenException for Dialog.show()
问题代码如下:
public static void showDialog(Context mContext)
{
Dialog dialog = new Dialog(mContext);
View view = LayoutInflater.from(mContext).inflate(layoutId, null);
dialog.show();
}
以上代码块如果mContext是Activity,窗口可以正常弹出,若mContext非Activity的话,就出现了
android.view.WindowManager$BadTokenException:
Unable to add Window -- token null is not for an application
解决办法:
修改代码:
public static void showDialog(Context mContext)
{
Dialog dialog = new Dialog(mContext);
View view = LayoutInflater.from(mContext)
.inflate(layoutId, null);
Window window = dialog.getWindow();
window.setType(WindowManager.LayoutParams
.TYPE_SYSTEM_ALERT);
dialog.show();
}
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
这个窗口类型很重要!