首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android AlertDialog.Builder 中 findViewById 返回 Null:需先獲取對話框 View

     編輯:程式設計綜合問答

錯誤代碼

AlertDialog.Builder adb = new AlertDialog.Builder(context);
adb.setView(LayoutInflater.from(context).inflate(R.layout.custom, null));
// ...
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker); // 錯誤:在 Activity 中找,不在對話框中

正確做法:保存充氣後的 View 引用

View dialogView = LayoutInflater.from(context).inflate(R.layout.custom, null);
AlertDialog.Builder adb = new AlertDialog.Builder(context);
adb.setView(dialogView);

adb.setPositiveButton("確定", (dialog, which) -> {
    DatePicker datePicker = dialogView.findViewById(R.id.datePicker); // 在 dialogView 上查找
    // 使用 datePicker...
});

adb.show();

關鍵點

  • AlertDialog.Builder 本身**不是 View**,無 findViewById 方法。
  • setView(View) 接收的 View 即為對話框內容根視圖,所有子控件查找都在該 View 上進行。
  • 若需在 onClick 後獲取輸入值,**必須**持有該 View 引用(final 或成員變量)。

進階:使用 DialogFragment

現代開發推薦繼承 DialogFragment,在 onCreateDialog 中構建,onCreateView 中充氣佈局,生命周期管理更完善。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved