尝试创建自定义警报对话框时出现空指针异常

时间:2015-10-10 15:22:59

标签: android nullpointerexception android-alertdialog

我制作了一个自定义提醒对话框:

final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                final FrameLayout frameView = new FrameLayout(this);
                builder.setView(frameView);


                final AlertDialog alertDialog = builder.create();
                LayoutInflater inflater = alertDialog.getLayoutInflater();
                dialoglayout = inflater.inflate(R.layout.customized_builder, frameView);
                alertDialog.show();

                ButtonFlat acceptButton = (ButtonFlat) findViewById(R.id.acceptButtonDialog);
                acceptButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });

                ButtonFlat declineButton = (ButtonFlat) findViewById(R.id.cancelButtonDialog);
                declineButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });

问题是,当我单击按钮显示此警告对话框时,它会在此行生成空指针异常:

        acceptButton.setOnClickListener(new View.OnClickListener()

1 个答案:

答案 0 :(得分:1)

似乎在运行时,操作系统不知道这个按钮在哪里。 试试这个:

ButtonFlat acceptButton = (ButtonFlat) dialoglayout.findViewById(R.id.acceptButtonDialog);
                acceptButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });

                ButtonFlat declineButton = (ButtonFlat) dialoglayout.findViewById(R.id.cancelButtonDialog);
                declineButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });

just add dialoglayout.findViewById()