簡體   English   中英

Android Studio-AlertDialog中的DatePicker,空對象引用

[英]Android Studio - DatePicker in AlertDialog, null object reference

我的應用程序中有一個活動,我希望用戶從DatePicker中選擇日期,該日期包含在AlertDialog中。 在AlertDialog中,我已將視圖設置為xml布局文件(僅包含LinearLayout,並帶有單個DatePicker。

代碼非常簡單,看起來像這樣,就在onCreate()下面。

AlertDialog.Builder alert  = new AlertDialog.Builder(this);
alert.setView(R.layout.activity_alertdialog_date);
DatePicker datePicker = (DatePicker) findViewById(R.id.Activity_AlertDialog_SetStartDate);
//  ... The rest of the AlertDialog, with buttons and all that stuff
alert.create().show()

布局顯示在AlertDialog中,並且該部分效果很好。 但是,當我嘗試添加此行時,出現空對象引用錯誤。

datePicker.setMinDate(System.currentTimeMillis() - 1000);

這是錯誤消息。

嘗試在空對象引用上調用虛擬方法'void android.widget.DatePicker.setMinDate(long)'

如何解決此問題,或以其他方式改進代碼? 我非常感謝我能獲得的所有幫助。 謝謝!

您的問題是您的findViewById在DatePicker視圖的錯誤位置查找。 在活動中調用findViewById將在活動的布局層次結構而不是對話框的布局上調用它。 您需要先為警報對話框增加布局,然后獲取對該視圖的引用。 這可以通過兩種方式實現。

可能最簡單的方法是在顯示對話框之前對視圖進行充氣並獲取引用:

View dialogView = LayoutInflater.from(this).inflate(R.layout.activity_alertdialog_date, false);
DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.Activity_AlertDialog_SetStartDate);

AlertDialog.Builder alert  = new AlertDialog.Builder(this);
alert.setView(dialogView);
//  ... The rest of the AlertDialog, with buttons and all that stuff
alert.create().show();

創建視圖后,還可以從警報對話框中獲取視圖:

AlertDialog.Builder alert  = new AlertDialog.Builder(this);
alert.setView(R.id.Activity_AlertDialog_SetStartDate);
//  ... The rest of the AlertDialog, with buttons and all that stuff
AlertDialog dialog = alert.create();

dialog.show();
DatePicker datePicker = (DatePicker) dialog.findViewById(R.id.Activity_AlertDialog_SetStartDate);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM