【问题标题】:Android Studio - DatePicker in AlertDialog, null object referenceAndroid Studio - AlertDialog 中的 DatePicker,空对象引用
【发布时间】:2017-10-19 23:21:13
【问题描述】:

我的应用中有一个 Activity,我希望用户从 DatePicker 中选择日期,该 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)' 在空对象引用上

我该如何解决这个问题,或者以其他方式改进我的代码? 我非常感谢我能得到的所有帮助。谢谢!

【问题讨论】:

  • 你想在哪里使用这条线datePicker.setMinDate(System.currentTimeMillis() - 1000);datePicker 是否在范围内?
  • 这是下一行。这一切都在我在 onCreate() 结束时调用的方法中。所以我在 setContentView(...) 下面的行中调用该方法
  • 问题的旁注:您可以链接您的 AlertDialog.Builder 调用,即 AlertDialog.Builder(this).setView(R.layout.my_layout).setButtonPositive(R.string.sweet_text).create().show() 以使您的代码更具可读性。

标签: java android android-studio datepicker android-alertdialog


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2015-11-24
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    相关资源
    最近更新 更多