我的应用程序中有一个 Activity ,我希望用户从包含在 AlertDialog 中的 DatePicker 中选择日期。在 AlertDialog 中,我将 View 设置为 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);
这是错误消息。
Attempt to invoke virtual method 'void android.widget.DatePicker.setMinDate(long)' on a null object reference
我该如何解决这个问题,或者以其他方式改进我的代码? 我真的很感谢我能得到的所有帮助。谢谢!
最佳答案
您的问题是您的 findViewById
在错误的位置查找 DatePicker View 。在 Activity 中调用 findViewById 将会在 Activity 的布局层次结构(而不是对话框的布局)上调用它。您需要首先膨胀警报对话框的布局,然后获取对 View 的引用。这可以通过多种方式实现。
可能最简单的方法是在显示对话框之前膨胀 View 并获取引用:
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();
您还可以在创建警报对话框后获取 View :
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);
关于java - Android Studio - AlertDialog 中的 DatePicker,空对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840248/