Java Android CalendarView selectedDateChanged 未更新

Java Android CalendarView selectedDateChanged not updating

我有一个 CalendarView,允许用户 select 日期和输入活动。

我有一个方法,每当 selected 日期如下更改时调用:

private void selectedDateChanged(CalendarView view, int year, int month, int dayOfMonth){
        //note: _Calendar is set to the view when activity loads hence the
        //the reason for not using view.getDate();
        Long timeSinceEpoch = _Calendar.getDate();

        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTimeInMillis(timeSinceEpoch);

        System.out.println(String.format("With gregorian calendar \n Day: %s \n Month: %s \n Year: %s",
                calendar.DAY_OF_MONTH, calendar.MONTH, calendar.YEAR));

    }

每次日期 selected 更改时都会调用该方法,问题是每次调用该方法时 GregorianCalendar 都不会更新。每当我 select 新的一天,

I/System.out: With gregorian calendar 
I/System.out:  Day: 5 
I/System.out:  Month: 2 
I/System.out:  Year: 1

已打印出来,并且在 select 编辑新日期时不会更新。

我不知道如何强制 GregorianCalendar 更新,CalendarView 的 javadoc 说 getDate() 应该 return 当前 selected 日期(自 unix 纪元以来的毫秒数)

System.out.println(String.format("With gregorian calendar \n Day: %s \n Month: %s \n Year: %s",
            dayOfMonth, month, year));

事实证明 Calendar.DAY_OF_MONTHCalendar.MONTHCALENDAR.YEAR 不是包含该信息的字段,而是代表您在调用 Calendar.get(); 时要查找的整数

所以修复这个问题相当简单,我了解到,正确的代码是:

private void selectedDateChanged(CalendarView view, int year, int month, int dayOfMonth){
        //note: _Calendar is set to the view when activity loads hence the
        //the reason for not using view.getDate();
        Long timeSinceEpoch = _Calendar.getDate();

        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTimeInMillis(timeSinceEpoch);

        //Notice instead of calling cal.DAY_OF_MONTH directly
        //I now call calendar.get(Calendar.DAY_OF_MONTH)
        System.out.println(String.format("With gregorian calendar \n Day: %s \n Month: %s \n Year: %s",
                calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR)));

    }