我已經創建了一個日曆,其中suer可以滾動瀏覽前一個月和下一個月的日曆,但我遇到的問題是用戶嘗試滾動到前一個月。Java日曆日期月份設置不正確
當用戶第一次點擊到前一個月運行應用程序時,它可以工作,但是當用戶再次點擊它時,它並不會妨礙我發送給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的代碼。問題是somwhere在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);
}
私人枚舉月{一月, 二月,三月,四月,五月,六月, 七月,八月,九月,十月, 十一月,十二月};
這不是你如何發佈代碼到Stackoverflow。每行代碼應該縮進4個空格。 – Pointy 2011-01-10 17:26:05
現在修正了隊友謝謝 – jonney 2011-01-10 17:30:40