开发者

DatePickerDialog shows the incorrect date if opened and then the date changes elsewhere

The code below shows a DatePickerDialog for the user to insert a date and works as expected. When the date is updated and the user closes the dialog the button which launched the DatePickerDialog is updated to show the selected date:

// 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();         
    }
};

But here is where i start having issues. The code below is the onClickListener for a button that adds one day to the timestampCalendar Calendar object. If i open the DatePickerDialog and close it, use the "plus1" button and then open the DatePickerDialog again it still shows the date from when i closed the DatePickerDialog the first time.

plus1.setOnClickListener(new View.OnClickListener() {           
        public void onClick(View view) {    
            timestampCalendar.add(Calendar.DATE, 1);
            currentTimestamp = timestampCalendar.getTimeInMillis();
            updateDateButton();
        }            
    });

I tried to fix this by calling the updateDate() method of the DatePickerDialog in the set listener but that doesn't work either.

Anyone have any ideas?


You need to call this line:

datepicker.updateDate(timestampCalendar.get(Calendar.DATE), timestampCalendar.get(Calendar.MONTH), timestampCalendar.get(Calendar.DATE));

When you are using the plus1 button. This will update the date picker.

You could actually just move this line of code into updateDateButton(); to stop repetition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜