简体   繁体   English

警报对话框无法添加窗口错误

[英]Alert Dialog Unable to add window Error

I'm trying to create AlertDialog from RecyclerView.Adapter with this code 我正在尝试使用此代码从RecyclerView.Adapter创建AlertDialog

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.AppTheme));
alertDialogBuilder.setView(R.layout.reserve_dialog);
alertDialogBuilder.create();
alertDialogBuilder.show();

but I'm getting this error in logcat: 但我在logcat中遇到此错误:

Theme: themes:{}
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

What is wrong? 怎么了?

Instead of getApplicationContext(), just use ActivityName.this. 代替getApplicationContext(),只需使用ActivityName.this即可。

   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new  ContextThemeWrapper(activity, R.style.AppTheme));
   alertDialogBuilder.setView(R.layout.reserve_dialog);
   alertDialogBuilder.create();
   if(!isFinishing()){
    alertDialogBuilder.show();
   }

you are passing context.getApplicationContext() 您正在传递context.getApplicationContext()

Instead of this pass activity context 代替此通过活动上下文

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.AppTheme));
    alertDialogBuilder.setView(R.layout.reserve_dialog);
    alertDialogBuilder.create();
    alertDialogBuilder.show();

删除getApplicationContext()并传递活动上下文。

Inside New Dialogue(youractivity.this, style) 内部新对话(youractivity.this,样式)

Hopefully it ll solved 希望它能解决

If you are creating the dialog inside the RecylerView.Adapter , pass the activity object in the constructor of the Adapter and use the object itself when creating the builder - 如果要在RecylerView.Adapter内部创建对话框,请在Adapter的构造函数中传递活动对象,并在创建构建器时使用该对象本身-

    if (!activity.isFinishing()) {
      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AppTheme));
      alertDialogBuilder.setView(R.layout.reserve_dialog);
      alertDialogBuilder.create();
      alertDialogBuilder.show();
    }

When you are displaying a dialog in a non activity class then you have to pass activity as a parameter. 当您在非活动类中显示对话框时,则必须将活动作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM