下面的代码显示了DatePickerDialog,供用户插入日期并按预期工作.当日期更新并且用户关闭对话框时,启动DatePickerDialog的按钮将更新以显示所选日期:
// Date Picker Section
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
Log.i(TAG, "Setting up new date picker "+timestampCalendar);
datepicker = new DatePickerDialog(this,
mDateSetListener,
timestampCalendar.get(Calendar.YEAR),
timestampCalendar.get(Calendar.MONTH),
timestampCalendar.get(Calendar.DATE));
return datepicker;
}
return null;
}
// updates the date we display in the Button
private void updateDateButton() {
timestampTextView.setText(monthName[timestampCalendar.get(Calendar.MONTH)]+", "+timestampCalendar.get(Calendar.DATE)+" "+timestampCalendar.get(Calendar.YEAR));
}
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
timestampCalendar.set(year, monthOfYear, dayOfMonth);
datepicker.updateDate(timestampCalendar.get(Calendar.DATE), timestampCalendar.get(Calendar.MONTH), timestampCalendar.get(Calendar.DATE));
updateDateButton();
}
};
但是这里是我开始遇到问题的地方.下面的代码是一个按钮的onClickListener,该按钮将一天添加到timestampCalendar Calendar对象.如果我打开DatePickerDialog并关闭它,请使用“ plus1”按钮,然后再次打开DatePickerDialog,它仍然显示我第一次关闭DatePickerDialog时的日期.
plus1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timestampCalendar.add(Calendar.DATE, 1);
currentTimestamp = timestampCalendar.getTimeInMillis();
updateDateButton();
}
});
我试图通过在设置侦听器中调用DatePickerDialog的updateDate()方法来解决此问题,但这也不起作用.
有人有想法么?
解决方法:
您需要致电此行:
datepicker.updateDate(timestampCalendar.get(Calendar.DATE), timestampCalendar.get(Calendar.MONTH), timestampCalendar.get(Calendar.DATE));
使用plus1按钮时.这将更新日期选择器.
您实际上可以将这行代码移到updateDateButton();中.停止重复.