创建AlertDialog是报错的原因

来源:互联网 发布:learnx mac 编辑:程序博客网 时间:2024/05/20 23:32

                代码如下:

                Builder builder = new Builder(getApplicationContext());

                builder.setItems(actionItems, new DialogInterface.OnClickListener() {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),which , Toast.LENGTH_SHORT).show();
                    }
                });

                builder.create().show();

报错:

Unable to add window -- token null is not for an application


原因是因为使用了getApplicationContext(),应该声明一个全局变量在onCreate()方法中将Activity.this赋值给全局变量然后使用。

修正后的代码如下:

                Builder builder = new Builder(mContext);
                builder.setItems(actionItems, new DialogInterface.OnClickListener() {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(mContext,which , Toast.LENGTH_SHORT).show();
                    }
                });
                builder.create().show();

0 0
原创粉丝点击