当我尝试打开对话框时,我收到以下Android异常。有人可以帮我理解发生了什么,我该如何解决这个问题?
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)
我猜 - 您是否正在尝试使用应用程序上下文创建Dialog?像这样的东西:
new Dialog(getApplicationContext());
这是错的。您需要使用Activity上下文。
你必须尝试:
new Dialog(YourActivity.this);
使用此和上下文不适用于我..但MyActivityName.this工作。希望这可以帮助任何需要它的人。
我通过在AndroidManifest.xml中添加以下user-permission解决了这个错误
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
此外,使用“活动名称”初始化警报对话框:
AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);
有关更多详细信息,请访问==> How to create Alert Dialog in Android
您可以继续使用getApplicationContext()
,但在使用之前,您应该添加此标志:dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
,并且不会显示错误。
并且不要忘记添加权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
在我的情况下,我试图像这样创建我的对话框:
new Dialog(getApplicationContext());
所以我不得不改变:
new Dialog(this);
它对我来说很好;)
尝试getParent()
在context
的争论地点,像new AlertDialog.Builder(getParent());
希望它会起作用,它对我有用。
我猜 - 你在尝试使用Dialog创建。
getApplicationContext()
mContext which is passed by activity.
如果您显示对话框非活动类,则必须将活动作为参数传递。
Activity activity=YourActivity.this;
现在它会很棒。
如果您发现任何问题,请告诉我。
我在上下文字段中尝试了这个:
this.getActivity().getParent()
它对我来说很好。这是一个从“片段”延伸出来的类:
public class filtro extends Fragment{...
我得到了同样的例外。我要解决的问题是将对话框的实例作为参数传递给函数并使用它而不是仅传递上下文然后使用getContext()。这个解决方案解决了我的问题,希望它能帮上忙
你好,如果你使用适配器可能有机会。 在适配器,getContext(),上下文或活动中使用任何对话框时,您需要知道的所有内容都无法正常工作。
这是我使用v.getRootView().getContext()
的技巧,其中v是您引用的视图对象。
例如。
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(v.getRootView().getContext(), date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
If you are getting this problem because of alert dialog.
Refer [here][1] But it is same concept.
[1]: https://stackoverflow.com/questions/6367771/displaying-alertdialog-inside-a-custom-listadapter-class
我得到了这个例外,当我尝试使用以下两种情况打开Cordova插件下的Progress Dialog时,
后来改变了这样,
new ProgressDialog(this.cordova.getActivity());
它对我来说很好。