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

时间:2016-04-28 12:39:53

标签: java android

我尝试使用此代码从AlertDialog创建RecyclerView.Adapter

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

但我在logcat中收到此错误:

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

有什么问题?

5 个答案:

答案 0 :(得分:1)

而不是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();
   }

答案 1 :(得分:1)

  

您正在传递context.getApplicationContext()

而不是传递活动上下文

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

内部新对话(youractivity.this,style)

希望它会解决

答案 4 :(得分:0)

如果要在RecylerView.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();
    }

当您在非活动类中显示对话框时,您必须将活动作为参数传递。