【发布时间】:2011-06-06 16:16:10
【问题描述】:
我创建了一个日历,用户可以在其中滚动浏览上个月和下个月的日历,但我遇到的问题是当用户尝试滚动到上个月时。
当用户在应用程序第一次运行时单击上个月时,它可以工作,但是当用户再次单击时,它并没有忽略我发送给 Calendar.Set() 的值是 100% 正确的,甚至对其进行了调试然而实际的日历并没有更新,因此与当前的月份相同!
下面是我的代码。
@Override
public void onClick(View v) {
// get current month
int currentMonth = mCurrentMonth.get(Calendar.MONTH);
Log.d(TAG, "day = " + mCurrentMonth.get(Calendar.DAY_OF_MONTH));
Log.d(TAG, "currentMonth in onClick = " + currentMonth);
if (v == mPreviousMonthButton) {
Log.d(TAG, "mPreviousMonthButton CLICKED ");
// if current month is january
// decrement the current year and set month to december
if (currentMonth == Calendar.JANUARY) {
int currentYear = mCurrentMonth.get(Calendar.YEAR);
mCurrentMonth.set(Calendar.YEAR, currentYear - 1);
mCurrentMonth.set(Calendar.MONTH, Calendar.DECEMBER);
} else {
// else decrement the month
Log.d(TAG, "currentMonth-- = " + currentMonth);
mCurrentMonth.set(Calendar.MONTH, currentMonth);
Log.d(TAG,
"month in previus button = "
+ mCurrentMonth.get(Calendar.MONTH));
}
// save the month
setDateForMonth();
} else if (v == mNextMonthButton) {
Log.d(TAG, "mNextMonthButton CLICKED ");
if (currentMonth == Calendar.DECEMBER) {
int currentYear = mCurrentMonth.get(Calendar.YEAR);
mCurrentMonth.set(Calendar.YEAR, currentYear + 1);
mCurrentMonth.set(Calendar.MONTH, Calendar.JANUARY);
} else {
currentMonth--;
mCurrentMonth.set(Calendar.MONTH, currentMonth + 1);
Log.d(TAG, "currentMonth++ = " + currentMonth + 1);
Log.d(TAG,
"month in next button = "
+ mCurrentMonth.get(Calendar.MONTH));
}
// save the month
setDateForMonth();
}
}
这里是实际更新 UI 的代码。问题出在 onClick 的某个地方,因为它在下面的代码中返回了错误的月份:
私人无效 setDateForMonth() {
monthList.clear();
Log.d(TAG, ".........setDateForMonth...........");
Log.d(TAG, "....................");
Log.d(TAG, "month = " + mCurrentMonth.get(Calendar.MONTH));
Log.d(TAG, "year = " + mCurrentMonth.get(Calendar.YEAR));
CalendarMonth[] months = CalendarUtils
.constructMonthViewArray(mCurrentMonth);
for (int i = 0; i < months.length; i++) {
monthList.add(months[i]);
Log.d(TAG, monthList.get(i).getDay());
}
Log.d(TAG, "....................");
mAdapter = new CalendarMonthAdapter(mContext, monthList);
mMonthGridView.setAdapter(mAdapter);
Months[] month = Months.values();
String currentMonth = month[mCurrentMonth.get(Calendar.MONTH)]
.toString();
String year = Integer.toString(mCurrentMonth.get(Calendar.YEAR));
mMonthLabel.setText(currentMonth + " " + year);
}
私有枚举 Months { 一月, 二月,三月,四月,五月,六月, 七月,八月,九月,十月, 11 月、12 月 };
【问题讨论】:
-
这不是您将代码发布到 Stackoverflow 的方式。每行代码应该缩进 4 个空格。