【发布时间】:2014-01-30 06:34:40
【问题描述】:
我正在 Android 上创建自己的日历 UI 实现。它的功能之一是通过简单地将日历的月份值增加或减少 1 来更改当前查看的月历。
默认日历值已使用:
this.currentCalendar = Calendar.getInstance(Locale.US);
下面是改变currentCalendar月份值的onClick监听器实现。
@Override
public void onClick(View v) {
int month = this.currentCalendar.get(Calendar.MONTH);
int year = this.currentCalendar.get(Calendar.YEAR);
SimpleDateFormat sdf = new SimpleDateFormat("MMM yyyy", Locale.US);
switch(v.getId()) {
case R.id.calendarNextMonthButton: // Next Button Clicked
month++;
break;
case R.id.calendarPrevMonthButton: // Prev Button Clicked
month--;
break;
}
this.currentCalendar.set(Calendar.MONTH, month);
Log.d("month", String.valueOf(this.currentCalendar.get(Calendar.MONTH)));
this.monthYearText = (TextView) this.v.findViewById(R.id.calendarMonthYearText);
this.monthYearText.setText(sdf.format(this.currentCalendar.getTime()));
}
初始化完成后,日历会正确显示 currentCalendar 月份和年份值,例如月 = 0(一月),年 = 2014。
当我第一次单击“下一步”按钮时,month 值增加了 1。currentCalendar 月份值设置使用:
this.currentCalendar.set(Calendar.MONTH, month); // debugger says month is 1
但是,当我试图显示 currentCalendar 的月份值时,调试器说月份值是 2(三月)而不是 1(二月)。这仅在第一次尝试单击“下一步”按钮时发生。下次我点击 Next 和 Prev 按钮时,日历月份会完美变化。
代码有什么问题吗?
PS:我将 java.util.Calendar 用于currentCalendar。
【问题讨论】: