Android - Custom Dialog throws NullPointerException when more than one button is defined
Here's the code that defines my custom dialog. When I show this dialog, it throws a NullPointerException at the commented line.
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);
sta开发者_StackOverflow中文版rtActivityForResult(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;
}
But when I remove my menu button and the menu.SetOnClickListener() method, it works fine! My retry button also works without a hitch. Why can't I add more than one button? Why does it throw the exception?
It looks like dialog.findViewById (R.id.ReturnToMenu);
is returning null. Can you check that you actually have a button with the correct ID? I'd guess that there is a typo somewhere in your "return to menu" button ID.
精彩评论