1
下面是定義我的自定義對話框的代碼。當我顯示這個對話框時,它在註釋行中拋出一個NullPointerException異常。當定義了多個按鈕時,Android - 自定義對話框會拋出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()方法,它工作正常!我的重試按鈕也可以順利運行。爲什麼我不能添加多個按鈕?它爲什麼拋出異常?
很難說沒有看到您的資源文件,但您是否試圖直接將兩個按鈕添加到視圖或不支持多個子對象的佈局? – 2011-01-07 18:23:40
如果您還發布對話框的佈局文件,它會有所幫助 – 2011-01-07 18:26:06