2017-10-19 45 views
0

我在我的应用程序中有一个活动,我希望用户从DateDicker中选择日期,它包含在AlertDialog中。在AlertDialog中,我已经将一个视图设置为一个xml布局文件(仅包含一个LinearLayout,带有一个DatePicker)。Android Studio - AlertDialog中的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); 

以下是错误消息

试图调用虚拟方法无效 android.widget.DatePicker.setMinDate(长)“对空对象引用

我怎样才能解决这个问题,或者改善我的代码以另一种方式? 我真的很感谢所有我能得到的帮助。谢谢!

+0

哪里你想使用这行'datePicker.setMinDate(System.currentTimeMillis() - 1000);'? 'datePicker'在范围内吗? – DigitalNinja

+0

这是非常接近的行。这是我在onCreate()的最后调用的方法。所以我在setContentView(...) – Fred

+1

的旁边调用方法:可以链接AlertDialog.Builder调用,即AlertDialog.Builder(this).setView(R.layout.my_layout) .setButtonPositive(R.string.sweet_text).create()。show()'使您的代码更具可读性。 – emerssso

回答

1

您的问题是您的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); 
+0

完美,谢谢! – Fred

相关问题