我正在尝试开发一个由按钮组成的屏幕,在其中单击按钮会启动自定义对话框。该对话框有一个ok按钮将其关闭。我为此编写了以下代码,但给了我NullPointerException

Dialog modalDialog;
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.input);

    Button modal = (Button)findViewById(R.id.ModalityButton);

    modal.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            modalDialog = new Dialog(Input.this);
            modalDialog.setContentView(R.layout.modality);
            modalDialog.setCancelable(true);
            Button ok = (Button) findViewById(R.id.modality_ok);

            ok.setOnClickListener(new OnClickListener() { // shows null pointer error at this line
                @Override
                public void onClick(View v) {
                    modalDialog.cancel();
                }
            });

            modalDialog.show();
        }
    });
}

最佳答案

在对话框的布局中搜索按钮ok

Button ok = (Button) modalDialog.findViewById(R.id.modality_ok);

10-08 09:07