Android的“无法添加窗口 - 令牌null不是一个应用程序的例外令牌、应用程序、窗口、不是

2023-09-03 20:28:20 作者:浅笑°

我,当我尝试打开一个对话框,得到以下的Andr​​oid例外。是否有人可以帮助我了解是怎么回事,我该如何解决这个问题?

  android.view.WindowManager $ BadTokenException:
  无法添加窗口 - 令牌null不是一个应用程序
    在android.view.ViewRoot.setView(ViewRoot.java:509)
    在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
    在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
    在android.app.Dialog.show(Dialog.java:241)
 

解决方案

我猜 - 你想用的应用程序上下文中创建对话框?事情是这样的:

 新的对话框(getApplicationContext());
 

这是错误的。您需要使用一个活动环境。

你必须尝试这样的:

 新的对话框(YourActivity.this);  
如何从智能手机或平板电脑上卸载 Android 应用程序

I get the following Android exception when I try to open a dialog. Can someone please help me understand what is going on and how can I fix this problem?

android.view.WindowManager$BadTokenException: 
  Unable to add window -- token null is not for an application
    at android.view.ViewRoot.setView(ViewRoot.java:509)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
    at android.app.Dialog.show(Dialog.java:241)

解决方案

I'm guessing - are you trying to create Dialog with an application context? Something like this:

new Dialog(getApplicationContext());

This is wrong. You need to use an Activity context.

You have to try like:

new Dialog(YourActivity.this);