使用 AlertDialog.Builder.setView() 時,若直接對 Activity 呼叫 findViewById 會找不到對話框內的元素。必須先膨脹佈局得到 View,再對該 View 查找。
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_signin, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView)
.setPositiveButton(R.string.login, (dialog, which) -> {
EditText user = dialogView.findViewById(R.id.loginUsername);
EditText pass = dialogView.findViewById(R.id.loginPassword);
String username = user.getText().toString();
String password = pass.getText().toString();
// 登入邏輯
})
.setNegativeButton(R.string.cancel, null)
.show();
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// 後續在 onClick 中用 findViewById(R.id.loginUsername) -> 找不到,拋 NPE
setView(View) 將佈局加入對話框視圖層級,不屬於 Activity 視圖樹。dialogView 參考。