在 MainActivity 中彈出自定義佈局的 AlertDialog 時發生崩潰,錯誤堆疊指向 setView() 或按鈕監聽器。本文通過真實代碼案例,教你如何快速定位並修復這類空指針異常。
LayoutInflater layoutInflater = LayoutInflater.from(this);
myLoginView = layoutInflater.inflate(R.layout.login, line); // line 為 null
Button button = (Button) findViewById(R.id.bt1);
button.setOnClickListener(this);
// onClick 內部
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("用戶登錄");
alertDialog.setView(myLoginView); // 這裡傳入的 myLoginView 可能有問題
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "確定", listener);
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", liss);
alertDialog.show();
line 變量未初始化(為 null),導致 myLoginView 佈局結構異常。liss 應為 listener,導致編譯錯誤或運行時異常。R.id.bt1 若不在 R.layout.login 中,findViewById 返回 null,後續設定監聽器拋出 NPE。// 1. 正確 inflate 佈局,父容器傳 null 即可(不附加到父視圖)
myLoginView = layoutInflater.inflate(R.layout.login, null);
// 2. 確保按鈕在 Dialog 佈局中,並從 myLoginView 找尋
Button btnConfirm = myLoginView.findViewById(R.id.bt_confirm);
Button btnCancel = myLoginView.findViewById(R.id.bt_cancel);
// 3. 統一監聽器寫法
DialogInterface.OnClickListener listener = (dialog, which) -> {
// 處理邏輯
};
alertDialog.setView(myLoginView);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "確定", listener);
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", listener);
NullPointerException 關鍵字,定位具體行號。myLoginView 進行非空判斷:if (myLoginView != null) { ... }。Dialog 崩潰多源於佈局 inflate 錯誤、控件引用為空、監聽器變量筆誤。養成「先檢查佈局 ID、再確認 inflate 參數、最後驗證監聽器綁定」的習慣,能避開 90% 的坑。