自定义对话框中的Android- Datepicker

时间:2015-07-01 14:08:04

标签: android android-fragments datepicker android-dialog android-datepicker

我有一个自定义对话框,上面有datepicker。在我的Fragment我有一个按钮,当我按下它时,对话框出现,我从datepicker中选择日期。我希望所选日期显示在textview的{​​{1}}上。我的代码如下:

这是我的主Fragment上包含Activity的对话框的代码:

Fragment

我从public int day; public int month; public int year; @SuppressLint("InflateParams") @SuppressWarnings("deprecation") public void SetDate(){ AlertDialog alertDialog = new AlertDialog.Builder(context).create(); alertDialog.setTitle("Select Date"); alertDialog.setIcon(R.drawable.action_reservations); LayoutInflater layoutInflater = LayoutInflater.from(context); View promptView = layoutInflater.inflate(R.layout.datepicker, null); alertDialog.setView(promptView); final DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1); final TextView PickedDate = (TextView) findViewById(R.id.pickeddate); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { day=datePicker.getDayOfMonth(); month=datePicker.getMonth() + 1; year=datePicker.getYear(); PickedDate.setText(new StringBuilder().append(day).append(" "). append("-").append(month).append("-").append(year)); } }); // Showing Alert Message alertDialog.show(); } 获取日期,月份和年份,并使用

将它们设置为我的textview
datepicker

同样在我的片段中,我使用下面的代码调用我的对话框:

PickedDate.setText(new StringBuilder().append(day).append(" ").
                            append("-").append(month).append("-").append(year));

当我运行我的应用程序时,我在这些行上得到了一个nullPointerException:

final Button SetDate = (Button)rootView.findViewById(R.id.selectdate);
        SetDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {       
                ((MainActivity) getActivity()).SetDate();            
            }  
            });

我做错了什么?提前致谢

1 个答案:

答案 0 :(得分:0)

尝试替换

final DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
final TextView PickedDate = (TextView) findViewById(R.id.pickeddate);

有了这个

final DatePicker datePicker = (DatePicker) promptView.findViewById(R.id.datePicker1);
final TextView PickedDate = (TextView) promptView.findViewById(R.id.pickeddate);