这是定义我的自定义对话框的代码。当我显示此对话框时,它会在注释行中抛出NullPointerException。
protected Dialog onCreateDialog (int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_SUCCESS_ID:
Context thisContext = this;
dialog = new Dialog(thisContext);
dialog.setContentView(R.layout.win_dialog);
dialog.setTitle("Stage One");
TextView timeScore = (TextView) dialog.findViewById(R.id.TimeScore);
timeScore.setText (elapsedTimeSec + "s");
TextView bestScore = (TextView) dialog.findViewById(R.id.BestScore);
bestScore.setText ("Best Score: (n/a)");
Button retry = (Button) dialog.findViewById(R.id.Retry);
retry.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
Intent retry = new Intent(v.getContext(), LevelOne.class);
startActivityForResult(retry, 0);
finish();
}
});
Button menu = (Button) dialog.findViewById (R.id.ReturnToMenu);
//Throws NullPointerException at this line
menu.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
Intent menu = new Intent(v.getContext(), Menu.class);
startActivityForResult(menu, 0);
finish();
}
});
break;
case DIALOG_GAMEOVER_ID:
break;
default:
dialog = null;
}
return dialog;
}
但是当我删除菜单按钮和menu.SetOnClickListener()方法时,它工作正常!我的重试按钮也顺利工作。为什么我不能添加多个按钮?为什么会抛出异常?
答案 0 :(得分:5)
看起来dialog.findViewById (R.id.ReturnToMenu);
返回null。你能检查一下你确实有一个ID正确的按钮吗?我猜你的“返回菜单”按钮ID中有一个错字。