Android - OnDateChangedListener - how do you set this?

落花浮王杯 提交于 2019-11-27 01:55:08
Christopher Orr

Once you've created your DatePicker, you need to initialize it with the date you want to display at first. That's the point at which you can add your listener.

See DatePicker.init(int, int, int, OnDateChangedListener).

Best way is

        DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {

                @Override
                public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
                    Log.d("Date", "Year=" + year + " Month=" + (month + 1) + " day=" + dayOfMonth);

                }
            });

This view is in fact a combination of four views, and they are :

Three Spinners

One CalendarView

As of the OnDateChangeListener, the object you passed in to the init method will be simply passed to the contained CalendarView, and I believe that you know that there is a setOnDateChangeListener method in the good old CalendarView...... ......

In the DatePicker class, there is a method called the getCalendarView, and it is the method you can call if you want to get your hands on the contained CalendarView.

Once you get your hands on the contained CalendarView, then, needlessly to say, you can call its setOnDateChangeListener

Something like this:

DatePicker myDatePicker = (DatePicker) findViewById(R.id.my_date_picker);
myDatePicker.getCalendarView().setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
    @Override
    public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
        Log.d("tag", "finally found the listener, the date is: year " + year + ", month "  + month + ", dayOfMonth " + dayOfMonth);
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!