CalenderView不存在 - 尝试实现DatePickerDialog

时间:2016-03-10 22:51:36

标签: java android datepicker calendar date-format

我正在尝试实现当用户点击文本框时弹出的DatePickerDialog。设置日期后,我正在尝试将文本框的文本设置为日期的格式化版本 - 简单,是吗?

我收到一个错误,告诉我传递给DatePickerDialog的onDateSet事件处理程序的DatePicker对象的日历视图不存在!!为什么会这样?我无法弄清楚。任何帮助将不胜感激。

仅供参考:我的目标是API 23,最低API 19,在API 22上运行

这是我的EditText的OnClickListener的代码...

private class DateClickListener implements View.OnClickListener{

    int mYear;
    int mMonth;
    int mDay;

    public void formatDate(long selectedDate){
        mDateText.setText(DateFormat.getDateInstance().format(selectedDate));
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        //To show current date in the datepicker
        Calendar mcurrentDate=Calendar.getInstance();
        mYear=mcurrentDate.get(Calendar.YEAR);
        mMonth=mcurrentDate.get(Calendar.MONTH);
        mDay=mcurrentDate.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog mDatePicker=new DatePickerDialog(CreateOuttingActivity.this, new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                formatDate(datepicker.getCalendarView().getDate());
            }
        },mYear, mMonth, mDay);
        mDatePicker.setTitle("Select date");
        mDatePicker.show();
    }
}

这是确切的错误跟踪:

03-10 17:52:20.750 21766-21766/... E/AndroidRuntime: FATAL EXCEPTION: main
                                                               Process: ..., PID: 21766
                                                               java.lang.UnsupportedOperationException: CalendarView does not exists for the new DatePicker
                                                                   at android.widget.DatePickerCalendarDelegate.getCalendarView(DatePickerCalendarDelegate.java:498)
                                                                   at android.widget.DatePicker.getCalendarView(DatePicker.java:377)
                                                                   at ...CreateActivity$DateClickListener$1.onDateSet(CreateActivity.java:70)
                                                                   at android.app.DatePickerDialog.onClick(DatePickerDialog.java:134)

1 个答案:

答案 0 :(得分:1)

后API 21不支持

getCalendarView()。 你可以试试这个 -

 DatePickerDialog mDatePicker=new DatePickerDialog(CreateOuttingActivity.this, new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                formatDate(getTimeFromDatePicker(view));
            }
        },mYear, mMonth, mDay);

其中getTimeFromDatePicker()可以定义为 -

public long getTimeFromDatePicker(DatePicker datePicker) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());

        return calendar.getTimeInMillis();
    }