I know this has been asked many times, but I can’t find an answer to suit my problem.
So I have an activity which has a button where its’ text is the current time (the time the activity was accessed). I can click on the button to show a TimePickerDialog where I can change the time, click the ‘Set’ button and the button updates with the new time. So far, so good, so basic.
My problem is that if I launch the TimePicker, change the time, click the Cancel button and then launch the TimePicker again, the displayed time is the time I cancelled instead of the original time from the button that launched it. If I cancel the TimePicker, I want it to forget any previous data.
Here is my code:
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
recordTime = new TimePickerDialog(this,mTimeSetListener, mHour, mMinute, true);
recordTime.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
recordTime.dismiss();
}
});
recordTime.setOnDismissListener(new OnDismissListener(){
@Override
public void onDismiss(DialogInterface arg0) {
recordTime.cancel();
recordTime.dismiss();
}
});
return recordTime;
}
return null;
}
// the callback received when the user sets the time in the dialog
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
updateTimeDisplay();
}
};
Each time a Dialog is opened with
showDialog()it passes throughonPrepareDialog(), simply reset the time here. If the user clickedSetthe new time is saved inmHourandmMinute, if the dialog is cancelled for any reason this restores the original data:You can easily call this in the OnCancelListener as well:
Also your original OnCancel and OnDismiss listeners seem redundant. What are you trying to do with them?
You should know that
onDismiss()is called if the user clicksSet,Cancel, or uses the back button. If the user clicksSetyou don’t want to call theonCancel()method isonDismiss(). Don’t treatonCancel()andonDismiss()as the same methods.