一旦我在对话框片段中使我的按钮可点击,应用程序就会崩溃

The app crashes as soon as i make my button clickable inside dialog fragment

这是我的代码,如果我删除按钮上的 onclicklistener,应用程序可以正常显示我想查看的对话框。但是,一旦我使其可点击,应用程序就会停止工作。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.dialogf, container,
            false);
    final Dialog dialog=getDialog();
    dialog.setTitle("DialogFragment Tutorial");
    Button button=(Button)dialog.findViewById(R.id.ok1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           dialog.dismiss();
        }
    });
    return rootView;
}

如果此 R.id.ok1 在您的布局 R.layout.dialogf 文件中。

然后在代码中你应该使用

Button button=(Button)rootView.findViewById(R.id.ok1);

rootView 而不是 dialog